UIElement positioning on canvas

I have a canvas and a red rectangle. Rectangle implemented MouseDown event MouseDown :

 private void RedRectangle_MouseDown(object sender, MouseButtonEventArgs e) { CreateMyBorder(); } 

It is assumed that the CreateMyBorder method creates a Border UIElement with the same size and position as the rectangle on the canvas, i.e. it should cover the red rectangle.

Copying the Width and Height properties of the red rectangle and setting them for the Border element is simple:

 myBorder.Height = RedRectangle.Height; myBorder.Width = RedRectangle.Width; 

However, copying the position of the red rectangle on the canvas seems impossible to me after 2 hours of trial and error! Expected:

 double x = RedRectangle.GetValue(Canvas.Left); double y = RedRectangle.GetValue(Canvas.Top); myBorder.SetValue(Canvas.Left, x); myBorder.SetValue(Canvas.Top, y); 

does not work because the values ​​of the variables x and y NaN . Why?

Please help, I can’t believe that something as trivial as getting and setting a UIElement position on a panel can be so annoying. Thank you

+7
source share
1 answer

You can use static functions on Canvas :

 Canvas.SetLeft(element, x); Canvas.SetTop(element, y); 

Beware, Canvas never display elements with Left or Top equal to double.NaN , which is the default value for Left and Top .

+12
source

All Articles