如何:对分层数据使用主-从模式How to: Use the Master-Detail Pattern with Hierarchical Data

此示例演示如何实现主-从方案。This example shows how to implement the master-detail scenario.

示例Example

在此示例中,LeagueListLeagues的集合。In this example, LeagueList is a collection of Leagues. 每个 League 都有一个 Name 和一个 Divisions集合,每个 Division 都有一个名称和 Teams的集合。Each League has a Name and a collection of Divisions, and each Division has a name and a collection of Teams. 每个 Team 都有一个团队名称。Each Team has a team name.

<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>

下面是该示例的一个屏幕快照。The following is a screenshot of the example. Divisions ListBox 会自动跟踪 Leagues ListBox 中的选定内容,并显示相应的数据。The Divisions ListBox automatically tracks selections in the Leagues ListBox and display the corresponding data. Teams ListBox 跟踪其他两个 ListBox 控件中的选定内容。The Teams ListBox tracks selections in the other two ListBox controls.

显示主-详细方案示例的屏幕截图。

在此示例中,需要注意以下两个事项:The two things to notice in this example are:

  1. 这三个 ListBox 控件绑定到同一个源。The three ListBox controls bind to the same source. 可以设置绑定的 Path 属性,以指定希望 ListBox 显示哪一级别的数据。You set the Path property of the binding to specify which level of data you want the ListBox to display.

  2. 必须在要跟踪的选定内容的 ListBox 控件上将 IsSynchronizedWithCurrentItem 属性设置为 trueYou must set the IsSynchronizedWithCurrentItem property to true on the ListBox controls of which the selection you are tracking. 设置此属性可确保选定项始终设置为 CurrentItemSetting this property ensures that the selected item is always set as the CurrentItem. 或者,如果 ListBoxCollectionViewSource中获取数据,则会自动同步选定内容和货币。Alternatively, if the ListBox gets it data from a CollectionViewSource, it synchronizes selection and currency automatically.

使用 XML 数据时,技术略有不同。The technique is slightly different when you are using XML data. 有关示例,请参阅对分层 XML 数据使用主-从模式For an example, see Use the Master-Detail Pattern with Hierarchical XML Data.

请参阅See also