Tuesday, January 26, 2016

XAML Binding a ComboBox to an Enum

Universal Apps: XAML Binding a ComboBox to an Enum

XAML sometimes has good news, and sometimes bad news for how easy we programmers can bind to types of lists.  Some "just work" and some are almost impossible.  The bad news is that most of the stackoverflow WPF solutions to binding a ComboBox to an enum don't work with Universal Apps.  The good news is that it's not actually hard to do.

The fundamentals are that
  1. You need to create a list of the enums.  A simple mechanism is something like Enum.GetValues(typeof(T)).Cast().ToList();
  2. XAML will happily bind a property of that list to a ComboBox ItemsSource
  3. Then bind the ComboBox SelectedItems to the an enum property

You will almost certainly want to display something a little nicer than just the enum values.  You can do this with a little IValueConverter.  It's possible to make a templated converter, so you can just pop in a standard class into your project.  The standard display XAML attribute isn't available for Universal, but it's trivial to make a small custom DisplayAttribute class. 

I've created a simple project with a nice helper classes; an entire sample project is now published on MSDN Samples pages along with complete instructions.
Update May 2021: MSDN Sample pages have gone to the great big bit-bucket in the sky. But you can see instructions and whatnot on this Github page. The page is the enumUtilities.cs file with the complete converter; it's also got complete instructions (that aren't quite as nice as having a sample).