2010-10-22 45 views
29

我有一个类。它描述了ViewModels的ListBox项目。一个列表框的两个itemtemplates

<ListBox ItemsSource="{Binding Fruits}"> 

而且我有

class BananaViewModel : FruitViewModel 

class AppleViewModel : FruitViewModel 

Fruits包含BananaViewModel S和这势必ItemsSourceAppleViewModel秒。

如何为苹果和香蕉制作不同的模板?它们应该在一个列表中,但具有不同的模板

回答

51

您可以通过指定DataType而不是x:Key来定义适用于特定类型的任何实例的DataTemplates。使用此方法,您不会将任何内容分配给ItemTemplate - 模板将自动应用。

<ListBox ItemsSource="{Binding Path=MixedList}"> 
    <ListBox.Resources> 
     <DataTemplate DataType="{x:Type local:BananaViewModel}"> 
      <TextBlock Text="{Binding Name}" Foreground="Yellow"/> 
     </DataTemplate> 
     <DataTemplate DataType="{x:Type local:AppleViewModel}"> 
      <TextBlock Text="{Binding Name}" Foreground="Red"/> 
     </DataTemplate> 
    </ListBox.Resources> 
</ListBox> 
+0

好东西,谢谢! – xSeder 2010-10-23 02:30:28

+2

感谢您提及您必须省略x:Key! – 2016-02-02 01:11:12

3

在XAML中的ListView上,您可以声明ItemTemplateSelector。此值将来自静态资源或类似资源。

您的模板选择器的实现应该实现DataTemplateSelector并且基本上包含'if'语句,该语句根据绑定项目的类型选择正确的DataTemplate。它可能会从传入的容器资源中找到DataTemplate(可能使用FindResource函数)。

编辑:好的链接也许? http://www.switchonthecode.com/tutorials/wpf-tutorial-how-to-use-a-datatemplateselector无效链接。

+0

请在这里添加示例代码 – 2017-08-12 19:41:58

相关问题