WPF绑定ComboBox到枚举(与扭曲) [英] WPF binding ComboBox to enum (with a twist)
问题描述
这个问题是我有这个枚举,但我不想要combobox显示枚举的值。这是枚举:
public enum Mode
{
[ ]
活动,
[说明(仅显示已选择)]
选择,
[说明(显示活动并选择)]
ActiveAndSelected $ b $所以在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
{
说明属性attrib =
attribArray [0] as DescriptionAttribute;
return attrib.Description;
}
}
ComboBox并显示其内容与GetDescription扩展方法?
谢谢!
解决方案我喜欢你的想法。但是GetCustomAttributes使用反射。
查看这篇文章:
WPF - 显示ComboBox控件中的枚举
http://www.infosysblogs.com/microsoft/2008/09/wpf_displaying_enums_in_combob.html
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 control
http://www.infosysblogs.com/microsoft/2008/09/wpf_displaying_enums_in_combob.html
这篇关于WPF绑定ComboBox到枚举(与扭曲)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!