如何:对分层数据使用主-从模式

此示例演示了如何实现大纲-详细信息方案。

示例

在此示例中,LeagueListLeagues 的集合。 每个 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>

下面是该示例的一个屏幕快照。 DivisionsListBox 自动跟踪 LeaguesListBox 中的所选项并显示相应的数据。 TeamsListBox 跟踪其他两个 ListBox 控件中的所选项。

Screenshot that shows a Master-detail scenario example.

此示例中有两点需要注意:

  1. 三个 ListBox 控件绑定到同一个源。 设置了绑定的 Path 属性以指定希望 ListBox 显示的数据级别。

  2. 必须在要跟踪其所选项的 ListBox 控件上将 IsSynchronizedWithCurrentItem 属性设置为 true。 设置此属性可确保所选项始终设置为 CurrentItem。 或者,如果 ListBoxCollectionViewSource 获取数据,它会自动同步所选项和货币。

使用 XML 数据时,此方法略有不同。 有关示例,请参阅如何:对分层 XML 数据使用大纲-详细信息模式

另请参阅