DataTemplateSelector
ItemTemplates
是根据 XAML 数据绑定中的项类型进行更改的推荐方法。DataTemplateSelector
不是 WP7 内置的,也不是 WP8 内置的。你必须在网上找到一个你喜欢的版本DataTemplateSelector
并使用它。或者只是自己动手,因为它大约有 5-10 行代码。
WindowsPhoneGeek 上有一篇关于WP7 中自定义 DataTemplateSelectors的好文章,wp7nl 项目基于该文章的DataTemplateSelector 基类。
<ListBox x:Name="listBox" HorizontalContentAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<local:FoodTemplateSelector Content="{Binding}">
<local:FoodTemplateSelector.Healthy>
<DataTemplate>
<StackPanel Orientation="Horizontal" Background="YellowGreen" Width="400" Margin="10">
<Image Source="{Binding IconUri}" Stretch="None"/>
<TextBlock Text="{Binding Name}" FontSize="40" Foreground="Black" Width="280"/>
<TextBlock Text="healty" />
</StackPanel>
</DataTemplate>
</local:FoodTemplateSelector.Healthy>
<local:FoodTemplateSelector.UnHealthy>
<DataTemplate>
<Border BorderBrush="Red" BorderThickness="2" Width="400" Margin="10">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding IconUri}" Stretch="None"/>
<TextBlock Text="{Binding Name}" FontSize="40" Width="280"/>
<Image Source="Images/attention.png" Stretch="None" Margin="10,0,0,0"/>
</StackPanel>
</Border>
</DataTemplate>
</local:FoodTemplateSelector.UnHealthy>
<local:FoodTemplateSelector.NotDetermined>
<DataTemplate>
<StackPanel Orientation="Horizontal" Background="Gray" Width="400" Margin="10">
<Image Source="{Binding IconUri}" Stretch="None"/>
<TextBlock Text="{Binding Name}" FontSize="40" Width="280"/>
<Image Source="Images/question.png" Stretch="None" Margin="10,0,0,0"/>
</StackPanel>
</DataTemplate>
</local:FoodTemplateSelector.NotDetermined>
</local:FoodTemplateSelector>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
如果您正在寻找更快速和更脏的解决方案,Prism 的 DataTemplateSelector不需要 C# 编码,因为它使用 DataTemplateSelector.Resources 集合来处理类型映射。这两个DataTemplateSelector
类都可以复制出来并在您的应用程序中使用。
1: <UserControl.Resources>
2: <DataTemplate x:Key="SelectorDataTemplate">
3: <prism:DataTemplateSelector Content="{Binding}"
4: HorizontalContentAlignment="Stretch"
5: IsTabStop="False">
6: <prism:DataTemplateSelector.Resources>
7: <DataTemplate x:Key="DataType1">
8: <StackPanel Orientation="Horizontal">
9: <TextBlock Text="{Binding ID}"/>
10: <toolkit:Separator />
11: <TextBlock Text="{Binding Name}" />
12: </StackPanel>
13: </DataTemplate>
14:
15: <DataTemplate x:Key="DataType2">
16: <StackPanel Orientation="Horizontal">
17: <TextBox Text="{Binding Index}" />
18: <toolkit:Separator />
19: <TextBox Text="{Binding Description}" />
20: </StackPanel>
21: </DataTemplate>
22:
23: </prism:DataTemplateSelector.Resources>
24: </prism:DataTemplateSelector>
25: </DataTemplate>
26: </UserControl.Resources>
还有更多DataTemplateSelectors
,包括:Odyssey Phone、UIMessage等。