Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Binding to Enumerations

0.00/5 (No votes)
14 Apr 2010 1  
How to bind to enumerations

Every now and then, you find yourself needing to bind some control or the 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 :).

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here