Question

If I have a class like the following whose code I cannot change, how can I add an EditorAttribute to s1 at run-time?

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.

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

How can I do this?

Was it helpful?

Solution

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.

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top