Positioning UIElement on a Canvas

Boris picture Boris · Dec 24, 2010 · Viewed 16.5k times · Source

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.

Answer

Simon Mourier picture Simon Mourier · Dec 24, 2010

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.