为什么我不能在WPF中移动路径?

时间:2019-10-09 19:17:15

标签: c# wpf path shapes

我尝试在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);
                }
            }
        }

PathShape,就像RectangleOnMouseMove都为两个控件执行一样。

为什么只有Rectangle在移动而Path没有移动?

1 个答案:

答案 0 :(得分:3)

改为使用ActualWidth和ActualHeight。宽度和高度(如果检查)为NaN。