2009-04-09 76 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