#485 – Binding a ComboBox to an Enumerated Type’s List of Values

You can easily bind a ComboBox (or ListBox) to an enumerated type’s values using an ObjectDataProvider.  The ObjectDataProvider allows calling a method and then using the result of the method call as a binding source.

To get the list of values for an enumerated type, we call the Enum.GetValues method, passing in the specific enumerated type.  In the example below, we do this in an ObjectDataProvider.

    <Window.Resources>
        <ObjectDataProvider x:Key="dateTimeKindValues" MethodName="GetValues" ObjectType="{x:Type sys:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="sys:DateTimeKind"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>

(This assumes that we’ve defined the sys namespace):

    xmlns:sys="clr-namespace:System;assembly=mscorlib"

The ObjectDataProvider is equivalent to the following code:

            DateTimeKind[] values = (DateTimeKind[])Enum.GetValues(typeof(DateTimeKind));

We can now use the output of the ObjectDataProvider as a data source for our binding.

    <ComboBox Height="25" Width="150"
              ItemsSource="{Binding Source={StaticResource dateTimeKindValues}}"/>

This gives us a ComboBox that lists the possible values of the DateTimeKind enumerated type.

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: