2012-02-29 225 views
1

如果我有一个类似以下的代码,我不能更改代码,那么如何在运行时将一个EditorAttribute添加到s1将运行时(动态)的EditorAttribute添加到对象的特殊属性

class TestClass 
{ 
    public String s1 {get;set;} 
    public String s2 {get;set;} 
} 

这个方法我试过,但它增加了一个EditorAttribute编辑器s2太,我不希望出现这种情况。

TypeDescriptor.AddAttributes(
    typeof(String), 
    new EditorAttribute ( 
      typeof(MyUITypeEditor), 
      typeof(UITypeEditor))); 

我该怎么做?

回答

0

您可以尝试使用CustomTypeDescriptor来实现您自己的类的类型描述符,并覆盖GetProperties方法以返回一组自定义属性描述符,这将使您有机会添加任何您想要的属性的自定义属性。

一旦你有了这个自定义类型描述符,你就可以绑定该类的一个实例(可以将TestClass类的实例包装到PropertyGrid控件中)。

类似以下内容:

public class TestClassTypeDescriptor : ICustomTypeDescriptor 
{ 
    private TestClass mInst; 

    public TestClassTypeDescriptor(TestClass inst) 
    { 
    mInst = inst; 
    } 

    //Implement ICustomTypeDescriptor 
} 


PropGridControl.SelectedObject = new TestClassTypeDescriptor(new TestClass()); 

您可能需要创建的PropertyDescriptorPropertyDescriptorCollection自己的衍生版本,但这些都是实现

很简单