views:

3357

answers:

1

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".

+2  A: 

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>
ArsenMkrt
But I want to bind to a property on the containing Window (defined in another XAML file), not on the UserControl.
Paul Baker
Than it will be better to have property in usercontrol and bind that property with window's property
ArsenMkrt
Can you create dependency property in UserControl? don't you add usercontrol in window? <UserControl MyProperty = {...binding with window's property }/>
ArsenMkrt
I see, thanks. But does anyone know why FindAncestor does not "just work"? Is its scope limited in some way, say, to within a single XAML file?
Paul Baker
do you try AncestorType={x:Type YourWindowType} instead of Window?
ArsenMkrt
I did try that - it still did not work.
Paul Baker
I don't know why it is not working to be honest, however my answer is better solution because parent type can be changed during development time
ArsenMkrt