如何:使用含階層式資料的主從式模式

此範例示範如何實作主要詳細資料案例。

範例

在此範例中, 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>

以下是範例的螢幕擷取畫面。 會自動 DivisionsListBox 追蹤 中的 LeaguesListBox 選取專案,並顯示對應的資料。 其他 TeamsListBoxListBox 個控制項中的追蹤選取專案。

Screenshot that shows a Master-detail scenario example.

在此範例中要注意的兩件事如下:

  1. 這三 ListBox 個控制項會系結至相同的來源。 您可以設定系 Path 結的 屬性,以指定要顯示的資料 ListBox 層級。

  2. 您必須在 IsSynchronizedWithCurrentItem 所追蹤選取專案的控制項上 ListBox ,將 屬性 true 設定為 。 設定此屬性可確保選取的專案一律設定為 CurrentItem 。 或者,如果 ListBoxCollectionViewSource 取得資料,則會自動同步選取專案和貨幣。

當您使用 XML 資料時,這項技術稍有不同。 如需範例,請參閱 搭配階層式 XML 資料使用主要-詳細資料 模式。

另請參閱