How to center an element in wpf canvas

Viewed 42919

How can I center an element in wpf canvas using attached properties?

4 Answers

Something like this.

double left = (Canvas.ActualWidth - element.ActualWidth) / 2;
Canvas.SetLeft(element, left);

double top  = (Canvas.ActualHeight - element.ActualHeight) / 2;
Canvas.SetTop(element, top);

The only way I know to do this is to figure out the size of the canvas, and then set the properties based off that. This can be done using an event handler for SizeChanged on the canvas:

parentCanvas.SizeChanged += new SizeChangedEventHandler(parentCanvas_SizeChanged);

void parentCanvas_SizeChanged(object sender, SizeChangedEventArgs e)
{
    parentCanvas.SetLeft(uiElement, (parentCanvas.ActualWidth - uiElement.ActualWidth) / 2);
    parentCanvas.SetTop(uiElement, (parentCanvas.ActualHeight - uiElement.ActualHeight) / 2);
}

You can put the Canvas and the element you want to be centered inside a Grid :

<Grid>
    <Canvas Width="200" Height="200" Background="Black" />
    <Button Width="50" Height="20" > Hello
    </Button>
</Grid>
Related