How to specify the position of an Ellipse shape on a canvas in WPF?

Joan Venge picture Joan Venge · Apr 8, 2011 · Viewed 53.2k times · Source

I am programmatically creating an Ellipse shape but I can't find any property that specifies its position. Lines have X1, Y1, X2, Y2, but there is no Center, Position, X, Y, etc on an Ellipse shape. How can I do this?

Answer

viggity picture viggity · Apr 8, 2011

Putting shapes in arbitrary places on the screen should probably be done so in a Canvas Panel (see @phoog's response). But if you're placing this in a Grid or some other panel instead, you could always modify the Margin property to place it where you want it.

If you wanted to do so by specifying the center point instead of the top left corner of the ellipse, you could do this:

Ellipse CreateEllipse(double width, double height, double desiredCenterX, double desiredCenterY)
{
    Ellipse ellipse = new Ellipse { Width = width, Height = height };
    double left = desiredCenterX - (width / 2);
    double top  = desiredCenterY - (height/ 2);

    ellipse.Margin = new Thickness(left, top, 0, 0);
    return ellipse;
}

I haven't checked that this does exactly what you want in the compiler, but hopefully you get the idea. Again, using Canvas would be the prefered method over using Margin inside of a non-Canvas panel, but the same principle of calculating left and top would still apply:

Canvas.SetLeft(ellipse, desiredCenterX - (width/2))
Canvas.SetTop(ellipse, desiredCenterY - (height/2))