How can I center an element in wpf canvas using attached properties?
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>
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.