ComboBox binding to enum, what did I do wrong? ComboBox binding to enum, what did I do wrong? wpf wpf

ComboBox binding to enum, what did I do wrong?


To access a nested type, you should use the "+" separator :

<ObjectDataProvider MethodName="GetValues"                    ObjectType="{x:Type sys:Enum}"                    x:Key="ContactExportTypes">    <ObjectDataProvider.MethodParameters>        <x:Type TypeName="local:Enums+ContactExportType" />    </ObjectDataProvider.MethodParameters></ObjectDataProvider>

By the way, there is a simpler way to bind to the values of an enum, without using an ObjectDataProvider. It's based on a custom markup extension :

<ComboBox ItemsSource="{local:EnumValues local:Enums+ContactExportType}"/>

Here is the code for the EnumValues 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);    }}


<ObjectDataProvider MethodName="GetValues"                    ObjectType="{x:Type local:Enums}"                    x:Key="ContactExportTypes">

should be

<ObjectDataProvider MethodName="GetValues"                    ObjectType="{x:Type sys:Enum}"                    x:Key="ContactExportTypes">

and

<x:Type TypeName="local:ContactExportType" /> 

should be

<x:Type TypeName="CEM.Marketing.Objects.ContactExportType"/>

the sys:Enum points to the Enum framework classthe typename in the parameter points to your fully qualified type-name.

check Bea Stollnitz's blog

    <ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type sys:Enum}" x:Key="odp">            <ObjectDataProvider.MethodParameters>                <x:Type TypeName="namespace.class.TShirtSizes"/>            </ObjectDataProvider.MethodParameters>    </ObjectDataProvider><ComboBox ItemsSource="{Binding Source={StaticResource odp}}" IsSynchronizedWithCurrentItem="true"/>