I want to add some custom PropertyGrid-centric Attributes to the object’s properties, to provide richer editing, hide some values and group them in categories, because that class I’m working with doesn’t provide such functionality and I can’t do anything about it.
Really, it’s for MS’s Application Settings that generates code, so you can’t extend it in any way property-wise. See my other question: Runtime AppSettings.settings editor dialog
Unlike others have suggested, it’s quite possible, and also not that hard. For example, you want to add some new attributes to some properties, which you can select at runtime based on some criteria.
There’re two helper classes we’ll need to implement this.
First goes
PropertyOverridingTypeDescriptor, it allows us to supply our own property descriptors for some properties, while keeping others intact:Few remarks:
ICustomTypeDescriptor, no worries here, we can get one for any type or it’s instance with theTypeDescriptor.GetProvider(_settings).GetTypeDescriptor(_settings)where _settings can be eitherTypeorobjectof that type.OverridePropertydoes just what we need, more on it later.The other class we need is the
TypeDescriptionProviderthat will return our custom type descriptor instead of the default one. Here it is:Fairly simple: you just supply the type descriptor instance on construction and here you go.
And finally, processing code. For example, we want all properties ending with
ConnectionStringin our object (or type)_settingsto be editable with theSystem.Web.UI.Design.ConnectionStringEditor. To achieve that, we can use this code:That’s it, now all properties ending with
ConnectionStringwill be editable throughConnectionStringEditor.As you can see, we just override some functionality of the default implementation every time, so the system should be fairly stable and behave as expected.