wpfdata-bindingxamlrelativesourcefindancestor

What exactly does WPF Data Binding's "RelativeSource FindAncestor" do?


I am currently working within a WPF user control (the root element of my XAML file is "UserControl"), which I know is being hosted inside a Window. How can I access a property of the Window using data binding?

Does anyone know why simply

<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type Window}}" Path="..." />

does not work? The error message I get is:

System.Windows.Data Warning: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Window', AncestorLevel='1''.

Edit: I ended up using a variation on ArsenMkrt's approach, so have accepted his answer. However, I am still interested in finding out why FindAncestor does not "just work".


Solution

  • The best way is to give a name to UserControl

    Create dependency property MyProperty in UserControl with two way binding and bind it in main Window, than bind in UserControl like this

    <UserControl x:Name = "myControl">
         <Label Content={Binding ElementName= myControl, Path=MyProperty}/>
    </UserControl>