Share via


HOW TO:使用含階層式資料的主從式模式

更新:2007 年 11 月

這個範例顯示如何實作主從式案例。

範例

在這個範例中,LeagueList 是 Leagues 的集合。每個 League 皆有一個 Name 與 Divisions 集合,而每個 Division 皆有一個名稱與 Teams 集合。每個 Team 各有一個小組名稱。

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

以下是範例的螢幕擷取畫面。Divisions ListBox 會自動追蹤 Leagues ListBox 中選取的項目,並顯示對應的資料。Teams ListBox 會追蹤其他兩個 ListBox 控制項中選取的項目。

主從式範例

在這個範例中應該注意兩件事:

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

  2. 您必須對要追蹤選取項目的 ListBox 控制項,將其 IsSynchronizedWithCurrentItem 屬性設定為 true。設定這個屬性可確保選取的項目一律會設定為 CurrentItem。不過,如果 ListBox 會從 CollectionViewSource 取得其資料,則它會自動同步處理選取項目與貨幣。

如需完整範例,請參閱使用 ObjectDataProvider 的主從式案例範例。使用 XML 資料時,這個方法會略有不同。如需範例,請參閱 HOW TO:使用含階層式 XML 資料的主從式模式

請參閱

工作

HOW TO:繫結至集合並根據選取項目顯示資訊

概念

資料繫結概觀

資料範本化概觀

參考

HierarchicalDataTemplate

其他資源

資料繫結範例

資料繫結 HOW TO 主題