Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Positioning UIElement on a Canvas

I have a canvas and a red rectangle laid on it. Rectangle has a MouseDown event handler implemented:

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

The CreateMyBorder method is supposed to create a Border UIElement with the same size and position as the rectangle on canvas, i.e. it is supposed to cover the red rectangle.

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

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

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

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

doesn't work as the x and y variable values are NaN. Why?

Please help, I cannot believe that something as trivial as getting and setting the UIElement's position on a panel can be so irritating. Thanks.

like image 958
Boris Avatar asked Dec 23 '10 23:12

Boris


1 Answers

You can use the 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.

like image 65
Simon Mourier Avatar answered Oct 13 '22 10:10

Simon Mourier