我有一个类FruitViewModel
。它描述了 ListBox
项的 ViewModel。
<ListBox ItemsSource="{Binding Fruits}">
我已经有了
class BananaViewModel : FruitViewModel
和
class AppleViewModel : FruitViewModel
Fruits
包含绑定(bind)到 ItemsSource
的 BananaViewModel
和 AppleViewModel
。
如何为苹果和香蕉制作不同的模板?它们应该位于一个列表中,但具有不同的模板
最佳答案
您可以通过指定不带 x:Key
的 DataType
来定义适用于特定类型的任何实例的 DataTemplate。使用此方法,您无需向 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>
关于wpf - 一个列表框有两个项目模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4001535/