Explain Ancestor relative source binding in WPF?


This relative binding helps to bind properties to the parent element properties. For example in the below XAML code we have a textbox which has two border’s as a parent. One border is having dark green and the other border is having dark red color as the border color.
The dark green color border is the parent element followed by dark red and the text box the child element at the end of the hierarchy.

<Border BorderBrush="DarkGreen">
   <Border BorderBrush="DarkRed”>
     <TextBox />
   </Border>
</Border>

Below is how the WPF application looks like when it runs.

Ancester1

Now we want the background color of the text box to be binded to one of the parent border
colors. To achieve the same we can use ancestor relative binding.
Below are some important properties in Ancestor type binding we need to know before we
writing the binding code.

AncestorType Which type of parent element is it?. Is it a border element , grid element etc.

AncestorLevel An element can have multiple parents. For example in the above XAML we
have two parents one with red color and the other with green. So this
property specifies which level of parent element we want to refer. Below is
the figure which depicts the levels. The red color border is level 1 and the
green color border is level 2.
So the nearest element becomes the first level and so on.

Binding This specifies which property we want to bind to. For the current example
we want to bind to border’s brush color.

Ancestorrelative

So the relative binding code with ancestor level 1 i.e. red looks as shown below. In case you are
confused with any of the properties please refer to the previous table for more information.

<TextBox Background="{Binding BorderBrush, RelativeSource={RelativeSource
FindAncestor, AncestorLevel=1, AncestorType={x:Type Border}}}"/>

So now the complete XAML with parent border element looks as shown in the below code.

<Border BorderBrush="DarkGreen"> <!-- Level 2 ->
<Border BorderBrush="DarkRed”> <!-- Level 1 ->
<TextBox Background="{Binding BorderBrush, RelativeSource={RelativeSource
FindAncestor, AncestorLevel=1, AncestorType={x:Type Border}}}"/>
</Border>
</Border>

Now if you run the above XAML code the textbox is binded with the back ground color of the
first border. If you change the ancestor level to 2 textbox background color will change to green.

Ancester2