Sdílet prostřednictvím


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

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

Example

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.

<Window
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:src="clr-namespace:SDKSample"
  Width="400" Height="180"
  Title="Master-Detail Binding" 
  Background="Silver">
  <Window.Resources>
    <src:LeagueList x:Key="MyList"/>


...


  <DockPanel DataContext="{Binding Source={StaticResource MyList}}">
    <StackPanel>
      <Label>My Soccer Leagues</Label>
      <ListBox ItemsSource="{Binding}" DisplayMemberPath="Name"
               IsSynchronizedWithCurrentItem="true"/>
    </StackPanel>

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

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

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 How to: Use the Master-Detail Pattern with Hierarchical XML Data.

See Also

Tasks

How to: Bind to a Collection and Display Information Based on Selection

Reference

HierarchicalDataTemplate

Concepts

Data Binding Overview

Data Templating Overview

Other Resources

Data Binding How-to Topics