Positioning UIElement on a Canvas
Asked Answered
D

1

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.

Dhiman answered 23/12, 2010 at 23:28 Comment(1)
GetValue returns an object too - you should cast it as double e.g. (double)RedRectangle.GetValue(Canvas.Top);Chausses
P
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.

Pinnatipartite answered 23/12, 2010 at 23:31 Comment(3)
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.Dhiman
Same idea: double left = Canvas.GetLeft(rectangle) to get rectangle's left.Pinnatipartite
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().Groundage

© 2022 - 2024 — McMap. All rights reserved.