简体   繁体   English

在运行时(动态地)将EditorAttribute添加到对象的特殊属性

[英]Adding EditorAttribute at Run-time (Dynamically) to an Object's special Property

If I have a class like the following whose code I cannot change, how can I add an EditorAttribute to s1 at run-time? 如果我有一个无法更改其代码的以下类,如何在运行时将EditorAttribute添加到s1

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

I tried this method, but it adds an EditorAttribute editor to s2 too and I don't want that. 我尝试了这种方法,但是它也向s2添加了EditorAttribute编辑器,但我不希望这样。

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

How can I do this? 我怎样才能做到这一点?

You could try implementing your own type descriptor for the class using CustomTypeDescriptor and override the GetProperties method to return a custom set of property descriptors which will give you the chance to add any custom attributes any property you wish. 您可以尝试使用CustomTypeDescriptor为类实现自己的类型描述符,并重写GetProperties方法以返回一组自定义的属性描述符,这将使您有机会将任何自定义属性添加到所需的任何属性。

Once you have this custom type descriptor, you can then bind an instance of that class (which could wrap an instance of the TestClass class) to the PropertyGrid control. 一旦有了此自定义类型描述符,就可以将该类的实例(可以包装TestClass类的实例)绑定到PropertyGrid控件。

Something like the following: 类似于以下内容:

public class TestClassTypeDescriptor : ICustomTypeDescriptor
{
   private TestClass mInst;

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

   //Implement ICustomTypeDescriptor
}


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

You may need to create your own derived versions of PropertyDescriptor and PropertyDescriptorCollection , but these are quite simple to implement 您可能需要创建自己的PropertyDescriptorPropertyDescriptorCollection的派生版本,但是实现起来很简单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM