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

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


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


I think using an ObjectDataProvider to do that is really tedious... I have a more concise suggestion (yes I know, it's a bit late...), using a markup extension :

<ComboBox ItemsSource="{local:EnumValues local:EmployeeType}"/>

Here is the code for the markup extension :

[MarkupExtensionReturnType(typeof(object[]))]public class EnumValuesExtension : MarkupExtension{    public EnumValuesExtension()    {    }    public EnumValuesExtension(Type enumType)    {        this.EnumType = enumType;    }    [ConstructorArgument("enumType")]    public Type EnumType { get; set; }    public override object ProvideValue(IServiceProvider serviceProvider)    {        if (this.EnumType == null)            throw new ArgumentException("The enum type is not set");        return Enum.GetValues(this.EnumType);    }}


Here is a detailed example of how to bind to enums in WPF

Assume you have the following enum

public enum EmployeeType    {    Manager,    Worker}

You can then bind in the codebehind

typeComboBox.ItemsSource = Enum.GetValues(typeof(EmployeeType));

or use the ObjectDataProvider

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

and now you can bind in the markup

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

Also check out:Databinding an enum property to a ComboBox in WPF