问题描述
问题是我有这个枚举,但是我不想让组合框显示枚举的值。这是枚举: 公开枚举模式
{
[说明(仅显示有效) ]
活动,
[描述(仅限显示选择)]
已选择,
[描述(显示活动和选定)]
ActiveAndSelected
}
所以在ComboBox中,而不是显示Active,Selected或ActiveAndSelected,我想显示DescriptionProperty对于枚举的每个值。我有一个名为GetDescription()的枚举扩展方法:
public static string GetDescription(this Enum enumObj)
{
FieldInfo fieldInfo =
enumObj.GetType()。GetField(enumObj.ToString());
object [] attribArray = fieldInfo.GetCustomAttributes(false);
if(attribArray.Length == 0)
{
return enumObj.ToString();
}
else
{
DescriptionAttribute attrib =
attribArray [0] as DescriptionAttribute;
return attrib.Description;
}
}
所以有一种方法可以将枚举绑定到ComboBox AND显示它的GetDescription扩展方法的内容?
谢谢!
我喜欢你的想法。但是GetCustomAttributes使用反射。你要做什么表现?
查看这篇文章:
WPF - 在ComboBox控件中显示枚举
Well the problem is that I have this enum, BUT I don't want the combobox to show the values of the enum. This is the enum:
public enum Mode
{
[Description("Display active only")]
Active,
[Description("Display selected only")]
Selected,
[Description("Display active and selected")]
ActiveAndSelected
}
So in the ComboBox instead of displaying Active, Selected or ActiveAndSelected, I want to display the DescriptionProperty for each value of the enum. I do have an extension method called GetDescription() for the enum:
public static string GetDescription(this Enum enumObj)
{
FieldInfo fieldInfo =
enumObj.GetType().GetField(enumObj.ToString());
object[] attribArray = fieldInfo.GetCustomAttributes(false);
if (attribArray.Length == 0)
{
return enumObj.ToString();
}
else
{
DescriptionAttribute attrib =
attribArray[0] as DescriptionAttribute;
return attrib.Description;
}
}
So is there a way I can bind the enum to the ComboBox AND show it's content with the GetDescription extension method?
Thanks!
I like the way you think. But GetCustomAttributes uses reflection. What is that going to do to your performance?
Check out this post:WPF - Displaying enums in ComboBox controlhttp://www.infosysblogs.com/microsoft/2008/09/wpf_displaying_enums_in_combob.html
这篇关于WPF绑定ComboBox到枚举(有一个扭曲)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!