In a project I had to create a little test application to create and edit objects of a referenced assembly. This was very early in the development stage, so the classes could possibly change a lot during the course of the project.
Instead of designing a UI for each class and getting into the process of changing it over and over again, I decided to use Reflection and the PropertyGrid control in winForms.
This worked well: getting all types via reflection, showing them in a treeview, creating an instance when the user selected a type in the treeview and showing it in the PropertyGrid. No problem there.
Even editing a property of an enumeration type was no problem.
But then I ran into a problem. Some of the enumerations were actually Flags. So the user must be able to select multiple values from the list. This is not supported by the PropertyGrid.
No wait! The items we wanted to test were defined in some business logic layer. We don’t want to add this attribute and a reference to Windows.Forms and so, to our business logic layer.
So, why can’t we just apply or set the attribute to the flag-properties at runtime?
Via reflection, using the PropertyDescriptor, you can check the attributes and get the list (or array) of attributes, but unfortunately this attribute list is readonly!
Unless you use reflection on the PropertyDescriptor as well. So, Reflection on Reflection objects. 🙂
When I then created an instance (
newObject = Activator.CreateInstance(type)) of these types, the attribute was taken into account and the checked listbox was shown in the PropertyGrid. Which was nice. 🙂