So, the web, and StackOverflow, have plenty of nice answers for how to bind a combobox to an enum property in WPF. But Silverlight is missing all of the features that make this possible :(. For example:
- You can't use a generic
EnumDisplayer
-styleIValueConverter
that accepts a type parameter, since Silverlight doesn't supportx:Type
. - You can't use
ObjectDataProvider
, like in this approach, since it doesn't exist in Silverlight. - You can't use a custom markup extension like in the comments on the link from #2, since markup extensions don't exist in Silverlight.
- You can't do a version of #1 using generics instead of
Type
properties of the object, since generics aren't supported in XAML (and the hacks to make them work all depend on markup extensions, not supported in Silverlight).
Massive fail!
As I see it, the only way to make this work is to either
- Cheat and bind to a string property in my ViewModel, whose setter/getter does the conversion, loading values into the ComboBox using code-behind in the View.
- Make a custom
IValueConverter
for every enum I want to bind to.
Are there any alternatives that are more generic, i.e. don't involve writing the same code over and over for every enum I want? I suppose I could do solution #2 using a generic class accepting the enum as a type parameter, and then create new classes for every enum I want that are simply
class MyEnumConverter : GenericEnumConverter<MyEnum> {}
What are your thoughts, guys?
Best Answer
Agh, I spoke too soon! There is a perfectly good solution, at least in Silverlight 3. (It might only be in 3, since this thread indicates that a bug related to this stuff was fixed in Silverlight 3.)
Basically, you need a single converter for the
ItemsSource
property, but it can be entirely generic without using any of the prohibited methods, as long as you pass it the name of a property whose type isMyEnum
. And databinding toSelectedItem
is entirely painless; no converter needed! Well, at least it is as long as you don't want custom strings for each enum value via e.g. theDescriptionAttribute
, hmm... will probably need another converter for that one; hope I can make it generic.Update: I made a converter and it works! I have to bind to
SelectedIndex
now, sadly, but it's OK. Use these guys:With this sort of binding XAML:
And this sort of resource-declaration XAML:
Any comments would be appreciated, as I'm somewhat of a XAML/Silverlight/WPF/etc. newbie. For example, will the
EnumToIntConverter.ConvertBack
be slow, so that I should consider using a cache?