c# - 获取类型的默认 PropertyDescriptors

标签 c# propertygrid propertyinfo propertydescriptor

我正在通过实现 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);

最佳答案

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

关于c# - 获取类型的默认 PropertyDescriptors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/735817/

相关文章:

c# - 如何在 PropertyGrid 中显示静态(共享)对象的属性?

c# - 如何通过反射获取类中某个属性的 "class type"?

c# - 忽略 PropertyInfo 中的集合属性

c# - 退出(Quit)实现

c# - 按钮点击不能正常工作

java - 有人知道 SWT 中的 PropertyEditor 或 PropertyGrid 之类的东西吗?

c# - 如何为 PLINQ 编写线程感知扩展函数?

c# - 如何编写自动缩放到系统字体和 dpi 设置的 WinForms 代码?

c# 窗体控件中的嵌套类(子类) “property grid”