How to: Use the Master-Detail Pattern with Hierarchical Data

This example shows how to implement the master-detail scenario.


In this example, LeagueList is a collection of Leagues. Each League has a Name and a collection of Divisions, and each Division has a name and a collection of Teams. Each Team has a team name.

  Width="400" Height="180"
  Title="Master-Detail Binding" 
    <src:LeagueList x:Key="MyList"/>
  <DockPanel DataContext="{Binding Source={StaticResource MyList}}">
      <Label>My Soccer Leagues</Label>
      <ListBox ItemsSource="{Binding}" DisplayMemberPath="Name"

      <Label Content="{Binding Path=Name}"/>
      <ListBox ItemsSource="{Binding Path=Divisions}" DisplayMemberPath="Name"

      <Label Content="{Binding Path=Divisions/Name}"/>
      <ListBox DisplayMemberPath="Name" ItemsSource="{Binding Path=Divisions/Teams}"/>

The following is a screenshot of the example. The Divisions ListBox automatically tracks selections in the Leagues ListBox and display the corresponding data. The Teams ListBox tracks selections in the other two ListBox controls.

Master-detail example

The two things to notice in this example are:

  1. The three ListBox controls bind to the same source. You set the Path property of the binding to specify which level of data you want the ListBox to display.

  2. You must set the IsSynchronizedWithCurrentItem property to true on the ListBox controls of which the selection you are tracking. Setting this property ensures that the selected item is always set as the CurrentItem. Alternatively, if the ListBox gets it data from a CollectionViewSource, it synchronizes selection and currency automatically.

The technique is slightly different when you are using XML data. For an example, see Use the Master-Detail Pattern with Hierarchical XML Data.

See Also

Bind to a Collection and Display Information Based on Selection
Data Binding Overview
Data Templating Overview
How-to Topics