2009-05-05 154 views
1

我有一组自定义的PropertyDescriptor,我也想添加类别,因此它们以更有组织的方式显示在PropertyGrid中。我希望每种类型的PropertyDescriptor都能进入特定的类别。向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是一个定义属性的类,其中包括名称,显示名称和类型。所以propDef.Attributes包含DisplayNameAttribute。

IntrinsicPropertyDef可以显示两个不同的自定义PropertyDescriptors IntrinsicPropertyDescriptor和InferedIntrinsicPropertyDescriptor。每个IntrinsicPropertyDescriptor应该有一个category属性“Intrinsic Properties”,并且每个InferedIntrinsicPropertyDescriptor都应该有一个category属性“Inferred Intrinsic Properties”。

回答

4

相信你可以重写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,系统必须找到它...分辨率规则是:

  • PropertyGrid,所述TypeConverter提供的属性,默认为属性的实例(见下文)
  • 一个实例:
    • ICustomTypeDescriptor检查
    • 否则检查注册的TypeDescriptionProvider为实例或类型
    • 否则反射使用
  • 对于类型:
    • 它检查注册TypeDescriptionProvider
    • 否则反射被用于
  • 对列表类型:
    • IListSource检查和解析为列表(处理继续)
    • ITypedList被选中
    • 否则,列表类型检查的非对象索引 - 即public SomeType this[int index] {get;}
      • 如果这样被发现,则该类型SomeType的属性被使用,如上面
    • 另有定义,否则如果列表不为空,在第一实例(list[0])的性质的使用,上述
    • 另有定义,元数据是不可用
+0

是的,你建议的类别覆盖工作完美。我知道如何使用构造函数,但并不认为使用静态方法来简化代码,我必须将其作为参数传递给构造函数。谢谢! – 2009-05-05 21:28:18