Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 675
user200783 Avatar asked Oct 28 '09 11:10

user200783


People also ask

What is binding RelativeSource?

The 'RelativeSource' property of the Binding class is used to bind the data from an element by it's relationship to the source element. RelativeSource is also a markup extension of type RelativeSource.

What are the different data binding modes available in WPF?

<TextBox x:Name="DestinationTextBox" Text="{Binding ElementName=SourceTextBox, Path=Text, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}" Margin="{StaticResource MarginTop}" Width="150"

What is XAML data binding?

Advertisements. Data binding is a mechanism in XAML applications that provides a simple and easy way for Windows Runtime Apps using partial classes to display and interact with data. The management of data is entirely separated from the way the data is displayed in this mechanism.

Which mechanism connects data in the code with the WPF elements?

Data binding is a mechanism in WPF applications that provides a simple and easy way for Windows Runtime apps to display and interact with data. In this mechanism, the management of data is entirely separated from the way data. Data binding allows the flow of data between UI elements and data object on user interface.


1 Answers

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> 
like image 101
Arsen Mkrtchyan Avatar answered Sep 27 '22 18:09

Arsen Mkrtchyan