ComboBox绑定到枚举,我做错了什么? [英] ComboBox binding to enum, what did I do wrong?
问题描述
我已经搜索了,它似乎很容易绑定枚举到组合框,只是通过ObjectDataProvider从静态Enum.GetValues方法检索枚举值作为字符串列表,但我不能让它工作。错误是类型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}}"
...
感谢,
Angela
Thanks, Angela
推荐答案
要访问嵌套类型, +分隔符:
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屋!