【问题标题】:Adding EditorAttribute at Run-time (Dynamically) to an Object's special Property在运行时(动态)将 EditorAttribute 添加到对象的特殊属性
【发布时间】:2012-02-29 16:24:53
【问题描述】:

如果我有一个类似以下的类,其代码无法更改,如何在运行时将 EditorAttribute 添加到 s1

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

我尝试了这种方法,但它也向 s2 添加了一个 EditorAttribute 编辑器,我不想要那个。

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

我该怎么做?

【问题讨论】:

    标签: c# propertygrid addattribute


    【解决方案1】:

    您可以尝试使用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 的派生版本,但这些实现起来非常简单

    【讨论】:

      猜你喜欢
      • 2011-01-03
      • 1970-01-01
      • 2012-01-12
      • 2011-10-05
      • 2017-10-14
      • 2017-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多