MVVM binding a ListView to an Enum with translation

Sometimes we need to visualize a list of enum values to the user, so he can make a
selection and if possible we would like to make this reusable for any enum used in our app.

But there are some problems when we would try to get this done… Enums are great for storing some kind of selection, but they are not easy to use in an MVVM list binding scenario! Certainly not if they need to be presented in a readable manner nor while different languages are supported.

But there is a way to get this done! Let me show you a solution while using a Windows Phone 8.1 store app, but the code will also work in Windows 8 store app and most of it will also run in a Windows Phone Silverlight app.

The enum we will be using…

The setup of this example is simple, we have a page with a ListView that’s bound to an enum in our ViewModel.

You’ll notice that the ItemSource is not binding to some collection! It’s the actual type of the enum and through the user of a converter we will return the needed display values. We are also showing the selected value inside a textblock, to show you that we are really getting an enum value!

In our ViewModel we have following properties.

The actual enum will be returned through the SelectionType property and the return type is System.Type. Also when the ListView has a selected index change, you’ll see that we’re using that current selected index to determine what enum value was actually chosen and we set that to the SelectedValue property.

So how do you initialize this, just by getting the type of your enum! In this example we init it in our constructor.

Now a ListView can’t do anything with an enum type, so we need to convert this in our EnumTypeToListConverter. The actual convert part looks like this.

We get the enum type as value parameter and use this to get all values of the given type through use of the general Enum.GetValues method. With this we have all values that the given enum has, but these aren’t yet usable to present inside the app! To fix this, we use a resource loader to get a nice display value for each enum value from the current loaded language resource! Finally we convert this to a list and return it to the ListView.

For this all to work you’ll need to add some resource files for each language you are going to support and inside each resource file you’ll need to add a display value for each enum value.

In our case we are using following format [enum type name]_[enum value]. So for our gender enum this gives following resource entries. For adding these resources, take a look at this good explanation here…

image

With all this in place you’ll get following result

 

As always a complete working version can be found on my github here…