How to use RelativeSource binding

Hello. Today I’m going to show how you can access certain element in tree via RelativeSource binding.

Let’s say we have this class:

public class Customer { public string FirstName { get; set; } }

<ListView ItemsSource="{Binding Customers}"> <ListView.ItemTemplate> <DataTemplate> <Grid> <TextBlock Text="{Binding FirstName}"/> </Grid> </DataTemplate> </ListView.ItemTemplate> </ListView>

And here is code that fills collection of customers:

public partial class MainWindow { public List<Customer> Customers { get; set; } public MainWindow() { InitializeComponent(); Customers = new List<Customer>(); for (int i = 1; i <= 10; i++) { Customers.Add( new Customer { FirstName = "Customer " + i }); } DataContext = this; } }

If you run the application you will see the following window:


As you probably know, each data item gets wrapped with ListViewItem (in case you use ListView).

You may wonder why, but recently I needed to access this ListViewItem in DataTemplate. Fortunately it’s easy to do with RelativeSource binding:

<DataTemplate> <StackPanel> <TextBlock Text="{Binding FirstName}"/> <TextBlock Text="{Binding Tag, RelativeSource={ RelativeSource AncestorType=ListViewItem}}"/> </StackPanel> </DataTemplate>

Here I’m using RelativeSource binding to allow binding system to find element that has ListViewItem type. When this element is found value from Tag property can be retrieved. Here is code that sets Tag property for each ListViewItem:

<ListView.ItemContainerStyle> <Style TargetType="ListViewItem"> <Setter Property="Tag" Value="123"/> </Style> </ListView.ItemContainerStyle>

If you run this application you will get the following window:


That’s basically all I wanted to show regarding RelativeSource binding. Bye Smile