Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
836 views
in Technique[技术] by (71.8m points)

wpf - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...