ComboBox 绑定到枚举,我做错了什么? [英] ComboBox binding to enum, what did I do wrong?

查看:20
本文介绍了ComboBox 绑定到枚举,我做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我四处搜索,似乎很容易将枚举绑定到组合框,只需通过静态 Enum.GetValues 方法中的 ObjectDataProvider 将枚举值作为字符串列表检索,但是我无法让它工作.错误是找不到类型 ContactExportType.

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.

我有一个名为 ContactExportType 的枚举,它驻留在 Enums 类中.此类是 CEM.Marketing.Objects 命名空间的一部分.

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

这就是我所拥有的:

<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}}"
...

谢谢,安吉拉

推荐答案

要访问嵌套类型,您应该使用+"分隔符:

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>

顺便说一下,有一种更简单的方法可以绑定到枚举的值,而无需使用 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}"/>

这是 EnumValues 标记扩展的代码:

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

这篇关于ComboBox 绑定到枚举,我做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆