How can I populate a WPF combo box in XAML with all the items from a given enum?

Drew Noakes picture Drew Noakes · Feb 11, 2009 · Viewed 23.9k times · Source

Say I have an enum with four values:

public enum CompassHeading
{
    North,
    South,
    East,
    West
}

What XAML would be required to have a ComboBox be populated with these items?

<ComboBox ItemsSource="{Binding WhatGoesHere???}" />

Ideally I wouldn't have to set up C# code for this.

Answer

casperOne picture casperOne · Feb 11, 2009

You can use the ObjectDataProvider to do this:

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

<ComboBox ItemsSource="{Binding Source={StaticResource odp}}" />

I found the solution here:

http://bea.stollnitz.com/blog/?p=28