Click here to Skip to main content
15,888,401 members
Articles / Desktop Programming / WPF

Binding to Enumerations

Rate me:
Please Sign up or sign in to vote.
3.22/5 (4 votes)
14 Apr 2010CC (Attr 3U) 16.5K   16   3
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.
XML
<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.

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

Thanks Paul :).

License

This article, along with any associated source code and files, is licensed under The Creative Commons Attribution 3.0 Unported License


Written By
Software Developer (Senior)
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalok article Pin
Donsw12-May-09 6:41
Donsw12-May-09 6:41 
GeneralRe: ok article Pin
Derek Lakin12-May-09 6:46
Derek Lakin12-May-09 6:46 
GeneralSimple Method here... Pin
stixoffire6-Apr-09 19:37
stixoffire6-Apr-09 19:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.