Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bind to DependencyProperty of Window

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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}}"/>
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading