Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ComboBox binding to enum, what did I do wrong?

I have searched around and it seems very easy to bind enums to combobox, just retrieve Enum values as a list of strings via an ObjectDataProvider from the static Enum.GetValues method, however i can't get it to work. The error is Type ContactExportType was not found.

I have an enum called ContactExportType, it resides on Enums class. This class is part of the CEM.Marketing.Objects namespace.

This is what i have:

<UserControl 
 xmlns:local="clr-namespace:CEM.Marketing.Objects"
 xmlns:sys="clr-namespace:System;assembly=mscorlib">

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

    </ObjectDataProvider>
    </Grid.Resources>

</Grid>
 <ComboBox 
        ItemsSource="{Binding {StaticResource ContactExportTypes}}"
...

Thanks, Angela

like image 910
Angela Avatar asked May 18 '09 15:05

Angela


1 Answers

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);
    }
}
like image 131
Thomas Levesque Avatar answered Sep 22 '22 11:09

Thomas Levesque