Como: Use the Master-Detail Pattern with Hierarchical Data
This example shows how to implement the master-detail scenario.
Exemplo
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.
The two things to notice in this example are:
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.
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.
A técnica é um pouco diferente quando você estiver usando XML de dados. For an example, see Como: Use the Master-Detail Pattern with Hierarchical XML Data.
Consulte também
Tarefas
Como: Bind to a Collection and Display Information Based on Selection
Referência
Conceitos
Revisão de Associação de Dados
Visão geral sobre Templating de dados