8

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.

animuson
  • 53,861
  • 28
  • 137
  • 147
Boris
  • 9,986
  • 34
  • 110
  • 147
  • GetValue returns an object too - you should cast it as double e.g. `(double)RedRectangle.GetValue(Canvas.Top);` – Brendan Feb 13 '14 at 13:45

1 Answers1

12

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.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Simon Mourier
  • 132,049
  • 21
  • 248
  • 298
  • Simon, thanks for the reply. This should solve the setter side for the `Border`. But how am I supposed to get the red rectangle's `Canvas.Left` and `Canvas.Top` properties? The way I wrote above always returns `NaN`. – Boris Dec 23 '10 at 23:38
  • 1
    Same idea: double left = Canvas.GetLeft(rectangle) to get rectangle's left. – Simon Mourier Dec 23 '10 at 23:44
  • It is worth noting two things: (1)that unless `Canvas.Left` is explicitly set, it will return NaN and (2) If you set `Canvas.Left` of an element, it may not actually reflect that setting. To exemplify this, set both `Canvas.Left` and `Canvas.Right` of the same element, then print out the values of `Canvas.GetLeft()` and `Canvas.GetRight()`. – Lucas Jun 06 '16 at 03:02