PropertyGrid Question

Closed
0
0

I am adding a combobox to the property grid but I only want to show certain fields like visible, enabled and backcolor.  IS there a way to do this?

Thanks,

Tim

  • You must to post comments
0
0

The PropertyGrid supports all (most) of the System.ComponentModel classes and patterns so you can use the TypeDescriptor classes to filter or change anything on any class. System.ComponentModel is quite a large subsystem in .NET but there are many examples available. I can give you a starting point:

This creates a custom type descriptor provider and  a custom type descriptor inheriting from the default one for the object selected. So in this case, this code won’t change anything, but you can add your code to filter or change any property. Custom type descriptors don’t have to inherit and can be “blank”.

public class MyProvider : TypeDescriptionProvider
{
   public MyProvider(object instance)
         : base(TypeDescriptor.GetProvider(instance))
   {
   }

   public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
   {
      return new MyDescriptor(base.GetTypeDescriptor(objectType, instance));
   }
}

public class MyDescriptor : CustomTypeDescriptor
{
  public MyDescriptor(ICustomTypeDescriptor parent)
       : base(parent)
  {
  }

  public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
  {
     // this is where you'd filter the properties.
     return base.GetProperties(attributes);
  }
}

The usage would be:

TypeDescriptor.AddProvider(new MyProvider(obj), obj);

From now on, any code anywhere asking for the properties of obj will go through MyDescriptor. You can also do that at the Type level. Be careful because TypeDescriptor keeps static collections so you have to do this registration only once for types and also only once for object instances.

While using the TypeDescriptor is extremely flexible since you can even add properties that don’t exist, change various attributes, add descriptions, etc. it can also get complex quickly.

Another way, which can be simpler and more manageable, is to simply create a wrapper class and expose only the properties you want to edit and simply use it as a proxy.

We could extend the PropertyGrid with a filter method, but the problem with filtering properties is that you can’t just pass one property and you need to create and pass a path array because properties are nested into other properties and the PropertyDescriptor class doesn’t have a Parent relation.

HTH

/Luca

 

 

  • Tim Larson
    Thank you Luca! That worked. I spent much time trying to make the properties not browseable but couldn’t get it to work. Seems like there should be an easier way but as long as there is a way to make it work that is awesome!
  • You must to post comments
Showing 1 result