我尝试在Wpf的UIElement
上移动(按住鼠标左键并拖动)Canvas
。
它适用于Rectangle
,但是当我将其尝试成Path
形状时,它不会移动。
这是布局,在画布内仅2个元素:
<Canvas Background='Beige'
Name='canvas'>
<Rectangle Width='50'
Height='50'
Fill='LightPink'
Canvas.Left='350'
Canvas.Top='175'
MouseMove='OnMouseMove'
Name='square' />
<Path Fill="Cyan"
Stroke="Black"
MouseMove='OnMouseMove'>
<Path.Data>
<GeometryGroup>
<EllipseGeometry Center="20, 40"
RadiusX="20"
RadiusY="40" />
<EllipseGeometry Center="20, 40"
RadiusX="10"
RadiusY="30" />
</GeometryGroup>
</Path.Data>
</Path>
</Canvas>
这是隐藏代码:
private void OnMouseMove(object sender, MouseEventArgs e)
{
if (e.Source is Shape shape)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
Point p = e.GetPosition(canvas);
Canvas.SetLeft(shape, p.X - shape.Width / 2);
Canvas.SetTop(shape, p.Y - shape.Height / 2);
}
}
}
Path
是Shape
,就像Rectangle
和OnMouseMove
都为两个控件执行一样。
为什么只有Rectangle
在移动而Path
没有移动?
答案 0 :(得分:3)
改为使用ActualWidth和ActualHeight。宽度和高度(如果检查)为NaN。