带有通用对象的DataTemplate [英] DataTemplate with an object taking a generic

查看:62
本文介绍了带有通用对象的DataTemplate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的对象

Assume I have an object as such

public interface ICustomObj
{
  ....
}

public class CustomObj<t> : ICustomObj
{
 //Impliments ICustomObj
}
</t>



我有一个不同的对象,该对象具有CustomObj的集合,并且它们具有不同的类型(例如,有些具有字符串,有些具有Date Time值.我想为



I have a different object that has a collection of the CustomObj''s and they have different types (e.g. some have strings and some have Date Time values. I would like to define a different data template for the type

CustomObj<string></string>

类型和

CustomObj<datetime></datetime>



能做到吗?



为了尝试使用转换器,我在尝试如何将通用值传递给转换器时遇到绊脚石.

我想要这样的事情:



Can this be done?



In an attempt to use the converter I am stumbling on how to pass the generic value to the converter...

I want to due something like this:

<ListBox ItemsSource="{Binding Path=EntryItems}">
 <ListBox.ItemTemplate>
   <DataTemplate Template="{Binding Path=Value, Converter=EntryConverter}"/>
 </ListBox.ItemTemplate>
</ListBox>





但是出现错误





But get the error

The property 'Template' cannot be set as a property element on template. Only Triggers and Storyboards are allowed as property elements.




解决方案是使用DataTemplateSelector.可以在此处 [




Solution is to use a DataTemplateSelector. An easy example can be found Here[^]

推荐答案

没有直接的支持将DataTemplate挂钩到通用类型.但是,解决此问题的普遍接受的方法是使用客户MarkupExtension来添加此功能.您可以在此处找到更多信息 [此处 [
There''s no direct support for hooking a DataTemplate to a generic type. However, the generally accepted way of working around this is to use customer MarkupExtensions to add this capability. You can find more on this here[^] and here[^].


无需创建其他为此的DataTemplate.使用IValueConverter并根据对象的类型转换值,例如如果object.GetType()== DateTime等.

Convert返回内容.
No need to Create different DataTemplate for this. Use IValueConverter and convert the value based on the type of the object e.g. if object.GetType() == DateTime etc.

Return the content from the Convert.


与其使用转换器,不如使用DataTemplateSelector来实现更多意义.我找到了一个简单的示例此处 [
Rather than using a converter a DataTemplateSelector made more sence. I found an easy example Here[^] that helped me build mine.


这篇关于带有通用对象的DataTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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