I want to create a CheckBox for toggling the Topmost property of the window.
If TopMost was a property of the ViewModel, I’d use this:
<CheckBox IsChecked="{Binding Path=Topmost}">Topmost</CheckBox>
But Topmost is a DependencyProperty on the Window in which the CheckBox is situated.
I tried the following:
<CheckBox IsChecked="{Binding Path=Topmost, Source={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}">Topmost</CheckBox>
but I get the following error at runtime:
System.Windows.Data Error: 40 : BindingExpression path error: 'Topmost' property not found on 'object' ''RelativeSource' (HashCode=12083439)'. BindingExpression:Path=Topmost; DataItem='RelativeSource' (HashCode=12083439); target element is 'CheckBox' (Name=''); target property is 'IsChecked' (type 'Nullable`1')
What’s my mistake here?
I could give the window an x:Name="MyWindow" and then use
<CheckBox IsChecked="{Binding Path=Topmost, ElementName=MyWindow}">Topmost</CheckBox>
instead, but I’d prefer to avoid x:Name if possible.
>Solution :
You have to set the RelativeSource property of the Binding instead of the Source property:
<CheckBox Content="Topmost"
IsChecked="{Binding Topmost,
RelativeSource={RelativeSource AncestorType=Window}}"/>