How to center an element in wpf canvas

Soham Dasgupta picture Soham Dasgupta · Feb 5, 2010 · Viewed 41.2k times · Source

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

Answer

Martin Braun picture Martin Braun · Mar 9, 2016

I came across this post, because I was searching for a way to center an element within a Canvas in XAML only, instead of using Attached Properties.

Just in case, you came for the same reason:

<Canvas x:Name="myCanvas">
    <Grid Width="{Binding ActualWidth, ElementName=myCanvas}" 
          Height="{Binding ActualHeight, ElementName=myCanvas}">
        <Label Content="Hello World!"
               HorizontalAlignment="Center"
               VerticalAlignment="Center" 
        />
    </Grid>
</Canvas>

One more thing, though

Beware that every solution here is a trap, depending on what you try to archive. Just because your element is within the Canvas on a hierarchical order, it will not be part of the Canvas itself. A Canvas is something to draw on and not to place controls in. So you cannot use the Canvas API for those controls, because the Grid is like an isolated overlay, obviously.

If you want a separated overlay, whilst the Canvas is your background, you are good to go with this solution.