WPF:我可以将枚举绑定到组合框吗?

时间:2009-12-02 13:03:55

标签: c# wpf-controls

我正在尝试让组合框显示一组预定义的值 - 在本例中为枚举。例如:

public enum Protocol
{
    UDP = 0,
    TCP,
    RS232
}

然而,我似乎无法完成它。这有可能吗?我试图使用数据绑定,但Blend只找到命名空间中的所有类,而不是枚举(显然不是对象)

2 个答案:

答案 0 :(得分:1)

将以下names绑定到ComboBox

var names = Enum.GetNames( typeof(Protocol) );

答案 1 :(得分:-1)

不知道WPF但是在webforms中(因为我使用MVP)我绑定了一个List>到了ddl。要获取列表,这里有一些代码

var pairs = new List<KeyValuePair<string, string>>();

            pairs.Add(new KeyValuePair<string, string>("Please Select", String.Empty));

            for (int i = 0; i < typeof(DepartmentEnum).GetFields().Length - 1; i++)
            {
                DepartmentEnum de = EnumExtensions.NumberToEnum<DepartmentEnum>(i);
                pairs.Add(new KeyValuePair<string, string>(de.ToDescription(), de.ToString()));
            }

            MyView.Departments = pairs;

它在枚举上使用扩展方法:

 public static class EnumExtensions
    {
        public static string ToDescription(this Enum en) 
        {
            Type type = en.GetType();

            MemberInfo[] memInfo = type.GetMember(en.ToString());

            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),false);

                if (attrs != null && attrs.Length > 0)

                    return ((DescriptionAttribute)attrs[0]).Description;
            }

            return en.ToString();
        }

        public static TEnum NumberToEnum<TEnum>(int number )
        {
            return (TEnum)Enum.ToObject(typeof(TEnum), number);
        }
    }