WPF绑定ComboBox到枚举(有一个扭曲) [英] WPF binding ComboBox to enum (with a twist)

查看:195
本文介绍了WPF绑定ComboBox到枚举(有一个扭曲)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是我有这个枚举,但是我不想让组合框显示枚举的值。这是枚举:

 公开枚举模式
{
[说明(仅显示有效) ]
活动,
[描述(仅限显示选择)]
已选择,
[描述(显示活动和选定)]
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控件中显示枚举
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屋!

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