簡體   English   中英

將類別屬性添加到PropertyDescriptor

[英]Add a category attribute to a PropertyDescriptor

我有一組自定義PropertyDescriptor,我也想添加類別,以便它們在PropertyGrid中以更有條理的方式顯示。 我希望每種類型的PropertyDescriptor都進入特定的類別。

我嘗試使用TypeDescriptor.AddAttributes()將屬性添加到現有PropertyDescriptor,但不添加category屬性。

CategoryAttribute intrinsicPropertyCategory = new CategoryAttribute("Intrinsic Properties");
currentDescriptor = new IntrinsicPropertyDescriptor(def);
TypeDescriptor.AddAttributes(currentDescriptor, new Attribute[] { intrinsicPropertyCategory });

我也嘗試在我的一個PropertyDescriptors的構造函數中使用TypeDescriptor.AddAttributes(),如下所示。 但它也不起作用。

public IntrinsicPropertyDescriptor(IntrinsicPropertyDef propDef): base(propDef.Key, propDef.Attributes)
{
this._type = propDef.Type;
this._key = propDef.Key;
this._readOnly = propDef.ReadOnly;

CategoryAttribute intrinsicPropertyCategory = new CategoryAttribute("Intrinsic Properties");
TypeDescriptor.AddAttributes(this, new Attribute[] { intrinsicPropertyCategory });
}

我寧願不花時間詳細說明我為什么要做我正在做的事情。 但在上面的示例中,IntrinsicPropertyDef是一個定義屬性的類,包括Name,Display Name和Type。 所以propDef.Attributes包含DisplayNameAttribute。

可以使用兩個不同的自定義PropertyDescriptors IntrinsicPropertyDescriptor和InferedIntrinsicPropertyDescriptor顯示IntrinsicPropertyDef。 每個IntrinsicPropertyDescriptor都應具有類別屬性“內在屬性”,並且每個InferedIntrinsicPropertyDescriptor都應具有類別屬性“推斷的內在屬性”。

相信你可以覆蓋Category

public override string Category { get {return "Foo";}}

對於其他場景; 通常使用自定義PropertyDescriptor ,您可以在構造函數中指定屬性。 您需要擴展Attribute[]參數以包含CategoryAttribute 如果需要進行任何處理,可以使用靜態方法 - 未經測試:

static Attribute[] AddCategory(Attribute[] attributes, string category) {
    Array.Resize(ref attributes, attributes.Length + 1);
    attributes[attributes.Length - 1] = new CategoryAttribute(category);
    return attributes;
}
public IntrinsicPropertyDescriptor(IntrinsicPropertyDef propDef)
     : base(propDef.Key, AddCategory(propDef.Attributes, "Foo"))
{...}

另外 - 請注意,對於要使用的PropertyDescriptor ,系統必須找到它...解析規則是:

  • 對於PropertyGridTypeConverter提供屬性,默認為實例的屬性(如下)
  • 對於一個實例:
    • 檢查ICustomTypeDescriptor
    • 否則它會檢查實例或類型的已注冊TypeDescriptionProvider
    • 否則使用反射
  • 對於一種類型:
    • 它檢查該類型的已注冊TypeDescriptionProvider
    • 否則使用反射
  • 列表:
    • 檢查IListSource並將其解析為列表(繼續處理)
    • 檢查ITypedList
    • 否則,檢查列表類型是否為非對象索引器 - 即public SomeType this[int index] {get;}
      • 如果找到了,則使用SomeType類型的屬性,如上所述
    • 否則,如果列表不為空,則使用第一個實例( list[0] )的屬性,如上所述
    • 否則,元數據不可用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM