WPF 列表中每个项目的不同项目模板? [英] Different item template for each item in a WPF List?

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

问题描述

我在列表控件中有很多项目.我希望每个项目都有一个不同的项目模板,具体取决于项目的类型.所以列表中的第一项是 ObjectA 类型,所以我希望它用 ItemTemplateA 呈现.第二个项目是 ObjectB 类型,所以我希望它有 ItemTemplateB 进行渲染.目前我只能使用 ItemTemplate 设置来为它们定义一个模板.有什么办法可以实现吗?

I have many items inside a list control. I want each item to have a different item template depending on the type of the item. So the first item in the list is a ObjectA type and so I want it to be rendered with ItemTemplateA. Second item is a ObjectB type and so I want it to have ItemTemplateB for rendering. At the moment I can only use the ItemTemplate setting to define one template for them all. Any way to achieve this?

推荐答案

ItemTemplateSelector 会起作用,但我认为在资源部分创建多个 DataTemplate 更容易然后给每个人一个DataType.如果项目生成器检测到匹配的数据类型,这将自动使用这个 DataTemplate?

the ItemTemplateSelector will work but I think it is easier to create multiple DataTemplates in your resource section and then just giving each one a DataType. This will automatically then use this DataTemplate if the items generator detects the matching data type?

<DataTemplate DataType={x:Type local:ObjectA}>
   ...
</DataTemplate>

还要确保您没有为 DataTemplate 设置 x:Key.
此处

Also make sure that you have no x:Key set for the DataTemplate.
Read more about this approach here

这篇关于WPF 列表中每个项目的不同项目模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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