WPF: How to draw a circle and drag it around?

"whatever it is" matters because placement of elements in WPF is highly dependent on the parent container. It's easy to move something 20px to the right inside a Canvas (just add to Canvas.Left), but it's much harder to do so in a Grid (you have to deal with Column, ColumnSpan and Margin).

There's a code project article describing how to drag elements inside a Canvas: Dragging Elements in a Canvas

If you want to move just that circle and not other controls in an existing Canvas/Grid; I suggest you use a DragCanvas (from the article) as an overlay over the normal Canvas/Grid.

As for the 'draw a circle' part: just use an Ellipse as element inside the DragCanvas.


I would define a canvas and an ellipse in the XAML file:

<Canvas Background="White" Name="canvas" Width="950" Height="500" MouseDown="MouseMove">
    <Ellipse Name="bola" Canvas.Left="130" Canvas.Top="79" Width="50" Height="50" Fill="Green"  />
</Canvas>

Notice that canvas has the attribute MouseDown="MouseMoveFunction". Whenever you click on the canvas, that event handler will be called. In case you want it to move as your mouse moves, use MouseMove="MouseMoveFunction"

Then just update the ellipse's position everytime you move your mouse. The following code goes in the function that is called on mouse events:

    private void MouseMove(object sender, MouseEventArgs e)
    {
        Point punto = e.GetPosition(canvas);
        int mouseX = (int)punto.X;
        int mouseY = (int)punto.Y;
        bola.SetValue(Canvas.LeftProperty, (double)mouseX); //set x
        bola.SetValue(Canvas.TopProperty, (double)mouseY); //set y

    }