在画布上定位 UIElement
我有一块画布,上面放了一个红色矩形。 Rectangle
实现了 MouseDown
事件处理程序:
private void RedRectangle_MouseDown(object sender, MouseButtonEventArgs e)
{
CreateMyBorder();
}
CreateMyBorder
方法应该创建一个具有相同大小的 Border
UIElement和位置作为画布上的矩形,即它应该覆盖红色矩形。
复制红色矩形的 Width
和 Height
属性并为 Border
元素设置它们很容易:
myBorder.Height = RedRectangle.Height;
myBorder.Width = RedRectangle.Width;
但是,复制红色矩形的位置经过两个小时的反复试验后,在画布上对我来说似乎是不可能的!预期:
double x = RedRectangle.GetValue(Canvas.Left);
double y = RedRectangle.GetValue(Canvas.Top);
myBorder.SetValue(Canvas.Left, x);
myBorder.SetValue(Canvas.Top, y);
不起作用,因为 x
和 y
变量值为 NaN
。为什么?
请帮忙,我不敢相信像获取和设置 UIElement 在面板上的位置这样微不足道的事情会如此令人恼火。谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在
Canvas
上使用静态函数:请注意,
Canvas
永远不会显示Left
或Top
等于 < code>double.NaN,这是Left
和Top
的默认值。You can use the static functions on
Canvas
:Beware,
Canvas
never display elements withLeft
orTop
equal todouble.NaN
, which is the default value forLeft
andTop
.