HOW TO:實作 CompositeCollection
更新:2007 年 11 月
範例
下列範例顯示如何使用 CompositeCollection 類別將多個集合和項目顯示為一份清單。在這個範例中,GreekGods 為 GreekGod 自訂物件的 ObservableCollection<T>。資料範本已定義成將 GreekGod 物件和 GreekHero 物件分別以金色和青色的前景色彩呈現。
<Window Background="Cornsilk"
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:SDKSample"
x:Class="SDKSample.Window1"
Title="CompositeCollections"
SizeToContent="WidthAndHeight"
>
<Window.Resources>
<c:GreekGods x:Key="GreekGodsData"/>
<XmlDataProvider x:Key="GreekHeroesData" XPath="GreekHeroes/Hero">
<x:XData>
<GreekHeroes >
<Hero Name="Jason" />
<Hero Name="Hercules" />
<Hero Name="Bellerophon" />
<Hero Name="Theseus" />
<Hero Name="Odysseus" />
<Hero Name="Perseus" />
</GreekHeroes>
</x:XData>
</XmlDataProvider>
<DataTemplate DataType="{x:Type c:GreekGod}">
<TextBlock Text="{Binding Path=Name}" Foreground="Gold"/>
</DataTemplate>
<DataTemplate DataType="Hero">
<TextBlock Text="{Binding XPath=@Name}" Foreground="Cyan"/>
</DataTemplate>
</Window.Resources>
<StackPanel>
<TextBlock FontSize="18" FontWeight="Bold" Margin="10"
HorizontalAlignment="Center">Composite Collections Sample</TextBlock>
<ListBox Name="myListBox" Height="300" Width="200" Background="White">
<ListBox.ItemsSource>
<CompositeCollection>
<CollectionContainer
Collection="{Binding Source={StaticResource GreekGodsData}}" />
<CollectionContainer
Collection="{Binding Source={StaticResource GreekHeroesData}}" />
<ListBoxItem Foreground="Red">Other Listbox Item 1</ListBoxItem>
<ListBoxItem Foreground="Red">Other Listbox Item 2</ListBoxItem>
</CompositeCollection>
</ListBox.ItemsSource>
</ListBox>
</StackPanel>
</Window>