PropertyDescriptor and Attributes

本文关键字:Attributes and PropertyDescriptor | 更新日期: 2023-09-27 18:25:14

我继承了PropertyDescriptor类以提供某种"动态"属性。我正在向PropertyDescriptor添加一些属性。这非常有效。

PropertyGrid中显示对象时,ReadOnlyAttribute工作,但EditorAttribute不工作!

internal class ParameterDescriptor: PropertyDescriptor {
    //...
    public ParameterDescriptor(/* ... */) {
        List<Attribute> a = new List<Attribute>();
        string editor = "System.ComponentModel.Design.MultilineStringEditor,System.Design";
        //...
        a.Add(new ReadOnlyAttribute(true));                         // works
        a.Add(new DescriptionAttribute("text"));                    // works
        a.Add(new EditorAttribute(editor, typeof(UITypeEditor)));   // doesn't work!
        //...    
        this.AttributeArray = a.ToArray();
    }
}

显示的对象使用继承的TypeConverter:

public class ParameterBoxTypeConverter: TypeConverter {
    public override bool GetPropertiesSupported(ITypeDescriptorContext context) {
        return true;
    }
    public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) {
        List<PropertyDescriptor> desc = new List<PropertyDescriptor>();
        //...
        ParameterDescriptor d = new ParameterDescriptor(/* ... */);
        desc.Add(d);
        //....
        return new PropertyDescriptorCollection(desc.ToArray());
    }

我被卡住了,因为PropertyGrid根本没有显示任何内容(我期望属性值为"…")。而且似乎没有办法调试!

那么我怎么才能发现这里出了什么问题呢
有没有一种方法可以调试到PropertyGrid等中?

PropertyDescriptor and Attributes

通过一些快速测试,名称需要完全限定:

const string name = "System.ComponentModel.Design.MultilineStringEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
attribs.Add(new EditorAttribute(name, typeof(UITypeEditor)));

在内部,它使用Type.GetType和:

var type1 = Type.GetType("System.ComponentModel.Design.MultilineStringEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
// ^^^ not null
var type2 = Type.GetType("System.ComponentModel.Design.MultilineStringEditor, System.Design");
// ^^^ null

当然,你可以使用:

attribs.Add(new EditorAttribute(typeof(MultilineStringEditor), typeof(UITypeEditor)));

或者,你可以override GetEditor,做任何你想做的事。