一个列表框的两个项目模板 [英] two itemtemplates for one listbox
问题描述
我有一个类FruitViewModel
.它描述了 ListBox
项的 ViewModel.
I've got a class FruitViewModel
. It describes ViewModels for ListBox
items.
<ListBox ItemsSource="{Binding Fruits}">
我有
class BananaViewModel : FruitViewModel
和
class AppleViewModel : FruitViewModel
Fruits
包含绑定到 ItemsSource
的 BananaViewModel
和 AppleViewModel
.
Fruits
contains BananaViewModel
s and AppleViewModel
s which is bound to ItemsSource
.
如何为苹果和香蕉制作不同的模板?它们应该在一个列表中,但具有不同的模板
How can I make different templates for apples and bananas? They should be in one list but have different templates
推荐答案
您可以通过指定不带 x:Key<的
DataType
来定义适用于特定类型的任何实例的 DataTemplates/代码>.使用此方法,您无需为 ItemTemplate
分配任何内容 - 模板会自动应用.
You can define DataTemplates that apply to any instance of a specific type by specifying the DataType
without an x:Key
. Using this method you don't assign anything to ItemTemplate
- the templates are applied automatically.
<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>
这篇关于一个列表框的两个项目模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!