A common thing I find myself doing when using the MVVM pattern within Windows Phone development is binding an Enum to a list picker. Recently I took some time to expand my libraries to help with this.
The first problem to tackle is converting the enum to something that the
ListPicker can use, an
IEnumerable<string>. Since I want this to run on Windows Phone and Windows 8 I chose to write code suitable to run in a Portable Class Library (PCL). I do this using reflection and creating an extension method similar to
This returns a list of strings based on the enum we used. I bind my ListPicker from my
MainPage.xaml.cs code behind file.
RemoveSpacesFromWords() method does exactly what you'd think. It replaces on any empty space characters in the returned strings. This gets you the first part of the way. Next, we need a way to bind to our ListPicker so we can use the
SelectedItem property. I do this by binding to a string property on my view model.
From there once my binding is setup I can update the backed property that holds the selected value of my enum. To do this I have code within the property setter.
The last extension method that I have is another enum extension that will return the enum property based on the string that is passed in. It is a pretty nifty method.
With this code I can now quickly bind a ListPicker from an enum value and easily extract the selected value from the enum for use within my view model. You can find my full enum extensions and string extensions on GitHub. If you found this helpful please let me know and share with others!