Binding WPF ComboBox Items to Enumeration

By Michael Detras

Binding to an enumeration is not as straightforward as it may seem. Enum's GetValues method must be used, along with ObjectDataProvider if binding is made in XAML.

Let's day we have the following WPF application main window and a DaysOfWeek enumeration. To get the values of the enumeration to be used in binding, we have to use the Enum.GetValues method. This takes a single method parameter, the enumeration type.

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
             InitializeComponent();
        }
    }

    public enum DaysOfWeek
    {
        Sunday,
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday
    }
}

To call this method in XAML, we have to use the ObjectDataProvider type. The following XAML code shows how to use ObjectDataProvider to fill a ComboBox with the enumeration values.

<Window x:Class="WpfApplication1.MainWindow"
         
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         
xmlns:system="clr-namespace:System;assembly=mscorlib"
         
xmlns:local="clr-namespace:WpfApplication1"
         
Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
         <ObjectDataProvider x:Key="DaysOfWeekProvider" MethodName="GetValues" ObjectType="system:Enum">
            <ObjectDataProvider.MethodParameters>
                 <x:TypeExtension TypeName="local:DaysOfWeek"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
     <Grid>
        <ComboBox
            
Margin="4" VerticalAlignment="Top" HorizontalAlignment="Left" Width="150"
             
ItemsSource="{Binding Source={StaticResource ResourceKey=DaysOfWeekProvider}}"/>        
    </Grid>
</Window>

Alternatively, you can just set the ItemsSource property directly in code like this.

comboBox.ItemsSource = Enum.GetValues(typeof(DaysOfWeek));

Related FAQs

Some developers new to WPF sometimes ask how to bind ComboBox items to a Dictionary. Usually, the SelectedValuePath is set to the Key property while the DisplayMemberPath is set to the Value property.
Binding WPF ComboBox Items to Enumeration  (3598 Views)