Search code examples
.netpropertygridtypedescriptor

Add property-level attributes dynamically using TypeDescriptor for PropertyGrid


I want to add attributes (like Browsable(false)) dynamically while displaying in the grid. Scenario is that I have a custom class with some public properties. However, I dont want all of the public properties to be displayed in the UI. Is there a way out?

I tried using TypeDescriptor. However, it works only at the type level and not at the property level. I couldn't find any help on how to use it at property-level.

Any pointers will be highly appreciated.


Solution

  • Actually It is possible, but I have to admit it is rather obscure and poorly documented. The key is to derive your own custom TypeDescriptorProvider from System.ComponentModel.TypeDescriptionProvider. Then you can return your own TypeDescriptor descendant.

    I did this to fix a rather nasty limitation regarding ViewModels and metadata in ASP.NET MVC, but you can just as well use it to insert your own extra metadata.