C
C#2y ago
FaNim

How to get and set position of an ui element via code wpf c#

Hello i want to create TextBoxes via code and set their position but i can't found how to even get the position or set what should i reference to?
7 Replies
Relevant
Relevant2y ago
Looks like you set it relative to the parent https://www.c-sharpcorner.com/UploadFile/mahesh/wpf-textbox3/
sev
sev2y ago
// Create a new TextBox control TextBox textBox = new TextBox(); // Set the position of the TextBox Canvas.SetLeft(textBox, xPosition); Canvas.SetTop(textBox, yPosition); // Add the TextBox to a Canvas control Canvas canvas = new Canvas(); canvas.Children.Add(textBox); // Get the position of the TextBox double x = Canvas.GetLeft(textBox); double y = Canvas.GetTop(textBox);
FaNim
FaNimOP2y ago
okay so i need to create canvas anyway
Canvas canvas = new();
TextBox box = new();
box.Width = 100;
box.Height = 25;
canvas.Children.Add(box);
Canvas.SetLeft(box, 150D * columns);
Canvas.SetTop(box, 50D * rows);
Canvas canvas = new();
TextBox box = new();
box.Width = 100;
box.Height = 25;
canvas.Children.Add(box);
Canvas.SetLeft(box, 150D * columns);
Canvas.SetTop(box, 50D * rows);
I have something like that and i still cant see my text box in window It doesnt work for me i sent my code up comment
Relevant
Relevant2y ago
Maybe your position calculations are off. Maybe try it at 0, 0 first just to make sure it's working.
FaNim
FaNimOP2y ago
okay i didn't knew that i need to set content of window as that canvas iam creating
Relevant
Relevant2y ago
Ah yeah, that too, the canvas would need to be added to the window
Klarth
Klarth2y ago
FYI, you aren't supposed to explicitly manage positions of elements in XAML-based frameworks. XAML frameworks have a really rich set of layout controls that you should be using. If you need to push a control a few pixels (say <= 20), then you can use Margin or Padding. For the rare case where you need to set absolute coordinates, then Canvas is indeed the go to. But free-form applications are rare outside of drawing apps and node design apps like https://github.com/miroiu/nodify And the freeform Canvas is usually confined to just one subview. Not the entire app window.
Want results from more Discord servers?
Add your server