此示例演示如何实现主详细信息方案。
示例:
在此示例中, LeagueList
是一个 Leagues
集合。 每个 League
都有一个 Name
和 Divisions
集合,每个 Division
都有一个名称和 Teams
集合。 每个 Team
团队都有一个团队名称。
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://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>
下面是示例的屏幕截图。
Divisions
ListBox 自动在 Leagues
ListBox 中跟踪所选内容,并显示相应的数据。 在其他两个 ListBox 控件中监控 Teams
ListBox 的选择。
此示例中要注意的两件事是:
必须在您跟踪的选定内容的ListBox控件上将IsSynchronizedWithCurrentItem属性设置为
true
。 设置此属性可确保所选项始终设置为 CurrentItem。 或者,如果 ListBox 从 CollectionViewSource 获取数据,它会自动同步所选项和货币。
使用 XML 数据时,此方法略有不同。 有关示例,请参阅 将 Master-Detail 模式与分层 XML 数据配合使用。