如何:使用含階層式資料的主從式模式
此範例示範如何實作主要詳細資料案例。
範例
在此範例中, 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 選取專案,並顯示對應的資料。 追蹤 Teams
ListBox 其他兩 ListBox 個控制項中的選取專案。
此範例中要注意的兩件事如下:
這三個 ListBox 控制項會系結至相同的來源。 您可以設定系 Path 結的 屬性,以指定要顯示的資料 ListBox 層級。
您必須在 IsSynchronizedWithCurrentItem 您要追蹤的選取範圍控制項上 ListBox ,將 屬性
true
設定為 。 設定此屬性可確保選取的專案一律設定為 CurrentItem 。 或者,如果 ListBox 從 CollectionViewSource 取得資料,它會自動同步選取範圍和貨幣。
當您使用 XML 資料時,這項技術會稍有不同。 如需範例,請參閱 搭配階層式 XML 資料使用Master-Detail模式。