I was trying to bind a property to the value of a property of the parent UserControl in WPF. When you google for it you get something pretty interesting: give a name to the user control right inside the user control XAML, then reference it with ElementName.

What I found after hours of torment was that this doesn't always work. I guess it only works up to the first item container in the logical tree and then stops. So that when I tried to use a property ImageSource of the user control in a Menu.Icon it failed!

My solution looks pretty ugly, but it does work in all cases!


<Image Source="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Controls:MyUserControl}},Path=MainMenuImageSource}"
Width="16" Height="16"></Image>



In other words: find the ancestor of the type of your user control and use it as the RelativeSource of the binding.

Comments

Post a comment