PropertyDescriptor和Attributes

时间:2013-07-29 09:02:50

标签: c# properties propertygrid propertydescriptor

我继承了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等?

1 个答案:

答案 0 :(得分:2)

通过一些快速测试,名称需要非常合格:

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做任何你想做的事。