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
Looks like you set it relative to the parent https://www.c-sharpcorner.com/UploadFile/mahesh/wpf-textbox3/
// 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);
okay so i need to create canvas anyway
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
Maybe your position calculations are off. Maybe try it at 0, 0 first just to make sure it's working.
okay i didn't knew that i need to set content of window as that canvas iam creating
Ah yeah, that too, the canvas would need to be added to the window
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.