1

I tried to move (hold the left mouse button and drag) a UIElement on a Canvas in Wpf.

It worked for a Rectangle but when I tried the same to a Path shape it does not move.

Here is the layout, just 2 elements inside a canvas:

<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>

And here is the code-behind:

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);
                }
            }
        }

The Path is a Shape like the Rectangle and OnMouseMove is executed for both controls.

Why only the Rectangle is moving and the Path isn't?

Themelis
  • 4,048
  • 2
  • 21
  • 45

1 Answers1

3

Use ActualWidth and ActualHeight instead. Width and Height, if you check, are NaN.

SledgeHammer
  • 7,338
  • 6
  • 41
  • 86
  • Do you know why the Path's Width/Height were 0 and the rectangle's not? – Themelis Oct 09 '19 at 19:52
  • 1
    @Themelis Width and Height are properties you set explicitly (sometimes). Generally you do NOT set them so the thing can be sized based on the content. In the case of the rectangle, you set them explicitly. For the path, you didn't... its implied by the stuff inside of it. Thus Width/Height will be NaN and the real sizes will be in Actual*… you should NEVER use Width/Height for UI calculations. Always use Actual* to consider scaling, transformations and other factors like size to content setups. – SledgeHammer Oct 09 '19 at 21:28
  • Thanks that helps – Themelis Oct 09 '19 at 21:29