RelativeSource in WPF

It is a Markup Extension. RelativeSource is used in Bindings. This Property tells about the source position where it lies relative to a given element. It can be of Four Types.

  • Self
  • FindAncestor
  • TemplatedParent
  • Previous

Self

It is used when an object binds its one property to its other property or to its parent.

Syntax:
“{Binding RelativeSource={RelativeSource Self},Path=PathToProperty}”

Example :

<Grid>
<Button Width=”100″ Height=”{Binding RelativeSource = {RelativeSource Self}, Path = Width}>” Button </Button>
</Grid>

Relative Binding Self

FindAncestor

Here the element bind its property to the property of any of its parent and grandparent. Here you give the AncestorType and AncestorLevel to decide whose property it is gonna use.

Syntax :
{Binding RelativeSource={RelativeSource FindAncestor,AncestorType= {x:Type typeOfAncestor}, AncestorLevel=2}, Path=PathToProperty}”

Example :

<Canvas Name=”Canvas1_Parent0″>
<Border Name=”Border1_Parent1″>
<Canvas Name=”Canvas2_Parent2″>
<Border Name=”Border2_Parent3″>
<StackPanel Name=”StackPanel1_Parent4″>
<StackPanel Name=”StackPanel2_Parent4″>
<StackPanel Name=”StackPanel3_Parent4″>
<TextBlock FontSize=”16″ Margin=”5″ Text=”Name of the ancestor”/>
<TextBlock FontSize=”16″ Margin=”50″ Text=”{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Border}, AncestorLevel = 2}, Path=Name}” Width=”200″/>
</StackPanel>
</StackPanel>
</StackPanel>
</Border>
</Canvas>
</Border>
</Canvas>

FindAncestor




TemplatedParent

It is used when we deal with Control Templates. Here we bind the property of ControlTemplate to the property of control to which we are applying the ControlTemplate.

Syntax :
Binding RelativeSource={RelativeSource TemplatedParent},Path=PathToProperty}

Example :

<Window.Resources>
<ControlTemplate x:Key=”template”>
<Canvas>
<Ellipse Height=”100″ Width=”150″ Fill=”LightBlue”></Ellipse>
<ContentPresenter Margin=”35″ Content = “{Binding RelativeSource = {RelativeSource TemplatedParent},Path=Text}”/>
</Canvas>
</ControlTemplate>
</Window.Resources>
<Canvas Name=”Parent0″>
<TextBox Margin=”50″
<TextBox Margin=”50″ Template=”{StaticResource template}” Height=”0″ Canvas.Left=”0″ Canvas.Top=”0″ Width=”0″ FontSize=”25″ Text=”Hi WPF”>
</TextBox>
</Canvas>

TemplatedParent

Previous

This is the least used mode of RelativeSource. It is used when we want to bind a property value to its previous value.
Syntax:
“{Binding RelativeSource={RelativeSource PreviousData},Path=PathToProperty}”