Saturday, November 3, 2012

WPF ObjectDataProvider - Binding Enum to ComboBox

Let's say we created some Enum data type. Now we want to show our Enum values on WPF ComboBox or ListBox. How do we do that?
In order to achieve this, in WPF we have an ObjectDataProvider class which provides mechanism for creation a XAML object available as a binding source.
Here is our Enum:
public enum TimePeriods
{
    Year,
    Month,
    Day,
    Hour,
    Minute
}
Now let's see how we bind it to a ComboBox in XAML:
<Window x:Class="WPFObjectDataProvider.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:local="clr-namespace:WPFObjectDataProvider"
        Title="CodeArsenal.Net" Height="59" Width="266">
    <Window.Resources>

        <ObjectDataProvider x:Key="timePeriodsFromEnum"
                            MethodName="GetValues" 
                            ObjectType="{x:Type sys:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="local:TimePeriods"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>

    </Window.Resources>
    
    <Grid>
        <ComboBox ItemsSource="{Binding Source={StaticResource timePeriodsFromEnum}}">
        </ComboBox>
    </Grid>
</Window>
As you can see in the code above I added ObjectDataProvider to Window.Resources. The GetValues() method gets an array of the values in an Enum. Since Enum is part of mscorlib assembly we must add a reference to it in our XAML. Finally we bind our static Enum resource to ItemSource of the ComboBox. This is what we have when we run the application:
WPF ObjectDataProvider - Binding Enum to ComboBox
Download the source code (Visual Studio 2010 Project).

5 comments:

  1. Thank you! I'll use it in my WPF app.

    ReplyDelete
  2. What's the difference b/w using ObjectDataProvider or simply using "Binding TimePeriods", as you did in another example of EmployeeView? Seems like it would be simpler to simply bind to the enum w/o involving the ObjectDataProvider. Can you explain?

    ReplyDelete
  3. Thanks man! I have created small article about binding to enums on ,y blog based on your article. http://druss.info/2015/01/wpf-binding-itemssource-to-enum/

    ReplyDelete
  4. and how about the other relevant ComboBox Properties like SelectedItem etc?
    And how would you do this in a DatagridComboBoxColumn?

    ReplyDelete
  5. Thanks!
    Is there a way to take information from the descripton attribute using data provider?

    ReplyDelete