2009-04-09 86 views
9

我正在通过实现ICustomTypeDescriptor来自定义对象类型在PropertyGrid中的显示方式。我允许用户创建自己的自定义属性,这些属性存储在单个字典的键和值中。我可以为这些值创建所有PropertyDescriptors,并在属性网格中查看它们。但是,我还想显示所有默认属性,否则在通过反射填充PropertyGrid而不是我的覆盖ICustomTypeDescriptor.GetProperties方法时将显示此属性。获取某个类型的默认PropertyDescriptors

现在我知道如何获得对象的类型,然后GetProperties(),但是这会返回一个PropertyInfo而不是ProperyDescriptor的数组。那么,如何将PropertyInfo类型的对象转换为PropertyDescriptor对象,以将其包含到我的收藏夹中,并使用自定义PropertyDescriptors

//gets the local intrinsic properties of the object 
Type thisType = this.GetType(); 
PropertyInfo[] thisProps = thisType.GetProperties(); 

//this line obviously doesn't work because the propertydescriptor 
//collection needs an array of PropertyDescriptors not PropertyInfo 
PropertyDescriptorCollection propCOl = 
    new PropertyDescriptorCollection(thisProps); 

回答

15
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(thisType); 

顺便说一句:这不包括你的ICustomTypeDescriptor的定制,但它包括通过TypeDescriptionProvider所做的任何的定制。

(编辑) 作为第二一边 - 比任何ICustomTypeDescriptorTypeDescriptionProvider要简单得多 - - 例如,你也可以通过提供TypeConverter调整PropertyGrid

[TypeConverter(typeof(FooConverter))] 
class Foo { } 

class FooConverter : ExpandableObjectConverter 
{ 
    public override PropertyDescriptorCollection GetProperties(
     ITypeDescriptorContext context, object value, Attribute[] attributes) 
    { 
     // your code here, perhaps using base.GetPoperties(
     // context, value, attributes); 
    } 
} 
+0

非常感谢! – Ross 2017-11-17 00:29:17