gpt4 book ai didi

c# - 将类别属性添加到 PropertyDescriptor

转载 作者:太空宇宙 更新时间:2023-11-03 22:27:26 24 4
gpt4 key购买 nike

我有一组自定义 PropertyDescriptor,我也想添加类别,以便它们以更有条理的方式显示在 PropertyGrid 中。我希望每种类型的 PropertyDescriptor 都属于特定的类别。

我尝试使用 TypeDescriptor.AddAttributes() 将属性添加到现有的 PropertyDescriptor,但未添加类别属性。

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 都应该有一个类别属性“Intrinsic Properties”,每个 InferedIntrinsicPropertyDescriptor 都应该有一个类别属性“Inferred Intrinsic Properties”。

最佳答案

相信您可以覆盖类别:

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]) 的属性,如上定义
    • 否则,元数据不可用

关于c# - 将类别属性添加到 PropertyDescriptor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/826437/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com