一个列表框的两个项目模板 [英] two itemtemplates for one listbox

查看:13
本文介绍了一个列表框的两个项目模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类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 包含绑定到 ItemsSourceBananaViewModelAppleViewModel.

Fruits contains BananaViewModels and AppleViewModels 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆