【问题标题】:Get the default PropertyDescriptors for a type获取类型的默认 PropertyDescriptors
【发布时间】:2023-03-09 16:00:02
【问题描述】:

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

现在我知道如何获取对象的类型,然后是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);

【问题讨论】:

    标签: c# propertygrid propertyinfo propertydescriptor


    【解决方案1】:
    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(thisType);
    

    顺便说一句:这不包括您的 ICustomTypeDescriptor 自定义设置,但它包括通过 TypeDescriptionProvider 进行的任何自定义设置。

    (编辑) 顺便说一句 - 您还可以通过提供 TypeConverter 来调整 PropertyGrid - 比 ICustomTypeDescriptorTypeDescriptionProvider 简单得多 - 例如:

    [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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-22
      • 1970-01-01
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 2010-10-03
      • 2022-06-19
      • 1970-01-01
      相关资源
      最近更新 更多