Derek Lakin

Binding to Enumerations

Every now and then you find yourself needing to bind a some control or other to the values of an enumeration, such as System.DayOfWeek. You’d think this would be fairly simple, but it’s actually trickier than you think.

I am fortunate to work with Paul Jackson, who’s a very clever chap, especially when it comes to WPF. Paul blogged about the ins and outs of binding to enumerations some time ago and I keep finding myself having to search for it, so I thought I’d add it to my own blog for safe keeping.

To summarise, you need to do the following:

  1. Add the appropriate XML namespace.
  2. Add an ObjectDataProvider with the MethodName set to GetValues.
  3. Set the ItemsSource property of your control.

Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" ...>Window.Resources>ObjectDataProvider x:Key="DayValues" MethodName="GetValues" ObjectType="{x:Type sys:Enum}">ObjectDataProvider.MethodParameters>x:Type TypeName="sys:DayOfWeek" />ObjectDataProvider.MethodParameters>ObjectDataProvider>Window.Resources>Grid> ...
ComboBox x:Name="_days" ItemsSource="{Binding Source={StaticResource DayValues}}" />
...
Grid>Window>

What Paul’s article doesn’t mention, is how to specify the SelectedValue. The following code example shows how to set the SelectedValue for our ComboBox above to be DayOfWeek.Monday.

ComboBox x:Name="_days"
ItemsSource="{Binding Source={StaticResource DayValues}}"
SelectedValue="{x:Static sys:DayOfWeek.Monday}"
/>

Thanks Paul :).