Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating / Modifying Enums at Runtime

I'm creating a program where the user has the option of creating their own custom properties that will ultimately be displayed in a PropertyGrid. Right now I don't want to mess with custom editors, so I'm only allowing primitive type properties (string, int, double, DateTime, bool etc.) that the PropertyGrid already has built in editors for.

However, I also want to give the user the option to create multiple choice properties where they can defined a list of possible values which in turn will show up as a drop down list in the PropertyGrid.

When I hard code an Enum in my code the property grid automatically shows properties of that enum as a drop down list. But can I create and or modify an enumeration at runtime so the user could add another property option, and go back to the PropertyGrid and see their new option in a drop down?

Update

Considering Patricks comment, I'm thinking that Enums are not the right way to go in this case. So instead how can I use a list of strings to populate a drop down in a PropertyGrid item? Would that require a custom editor?

like image 342
Eric Anastas Avatar asked Apr 14 '09 02:04

Eric Anastas


1 Answers

The answer is in a simple class: TypeConverter. (and yes, enums are not suitable here).

Since I have not a lot of details, I will assume that you have a PropertyGrid "linked" to a target instance by the SelectedObject property and that your target instance implements ICustomTypeDescriptor so that you can add properties (i.e. PropertyDescriptors) at runtime. I don't know your design but if you are not doing like this, I advise you to have a look at it.

Now let's say that you add a string property and that you want to let your user specify a set of constraints for this property. Your UI let's the user enter a set of strings and you get a list of strings as a result. Maybe you keep a dictionary of properties in your target instance so let's assume this new list is stored there too.

Now, just write a new converter derived from TypeConverter (or StringConverter maybe in this example). You will have to override GetStandardValuesSupported to return true and GetStandardValues to return the list of strings (use the context parameter to access the Instance property and its list of strings). This converter will be published by your PropertyDescriptor with the PropertyDescriptor.Converter property.

I hope this is not too nebulous. If you have a specific question on this process, just let me know.

like image 76
Nicolas Cadilhac Avatar answered Oct 06 '22 23:10

Nicolas Cadilhac