我正在通过实现 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
- 比 ICustomTypeDescriptor
或 TypeDescriptionProvider
简单得多- 例如:
[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/