我定义了一个自定义 ExpandableObjectConverter
对于集合:
internal class ExpandableCollectionConverter : ExpandableObjectConverter
{
public override PropertyDescriptorCollection GetProperties(
ITypeDescriptorContext context, object value, Attribute[] attributes)
{
//implementation that returns a list of property descriptors,
//one for each item in "value"
}
}
还有一个名为ExpandableObjectManager
的代理类,本质上是这样做的:
TypeDescriptor.AddAttributes(type,
new TypeConverterAttribute(typeof(ExpandableCollectionConverter)));
使用这个方法:
public static class ExpandableObjectManager
{
public static void AddTypeDescriptor(Type tItem)
{
//eventually calls TypeDescriptor.AddAttributes
}
}
是否有可能以所有通用的方式添加类型描述符 List<T>
将在属性网格中扩展?例如,给定一个简单的 Employee
类:
class Employee
{
public string Name { get; set; }
public string Title { get; set; }
public DateTime DateOfBirth { get; set; }
}
我可以做到这一点(它有效,但仅适用于 List<Employee>
):
ExpandableObjectManager.AddTypeDescriptor(typeof(List<Employee>));
我想涵盖所有 T
,不只是 Employee
,而不必为每个可能的类写 1 行。我试过了 - 没用:
ExpandableObjectManager.AddTypeDescriptor(typeof(List<>));
TL;DR:设置为 SelectedObject
时列表的默认 View 在属性网格中:
预期结果:
无需为 List<Employee>
添加类型描述符, 而不是为所有 List<T>
提供一些通用处理程序.
最佳答案
编辑:我添加了第三种可能性。
我认为这些都不是很好的解决方案,但有以下三种可能性:
将 TypeConverterAttribute 添加到通用类型实现的接口(interface)。这里的缺点是您可能无法准确命中目标类型,但它比选项 2 更好,因为它更专注于您想要的类型。
TypeDescriptor.AddAttributes(typeof(IList), new
TypeConverterAttribute(typeof(ExpandableCollectionConverter)));
将 TypeConverterAttribute 添加到 object
类型。缺点是这会使您的类型转换器成为项目中所有类型的类型转换器。
TypeDescriptor.AddAttributes(typeof(object), new
TypeConverterAttribute(typeof(ExpandableCollectionConverter)));
创建您自己的继承自 List<>
的列表类型并让它在静态构造函数中注册自己
public class CustomList<T> : List<T>
{
static CustomList()
{
TypeDescriptor.AddAttributes(typeof(CustomList<T>), new TypeConverterAttribute(typeof(ExpandableCollectionConverter)));
}
}
关于c# - 将类型描述符添加到所有 List<T> 以实现属性网格扩展的通用实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27570488/