代码之家  ›  专栏  ›  技术社区  ›  Maciek

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

  •  1
  • Maciek  · 技术社区  · 15 年前

    我试图让组合框显示一组预先定义的值——在本例中是一个枚举。例如:

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

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

    2 回复  |  直到 15 年前
        1
  •  1
  •   Winston Smith    15 年前

    束缚 names 下面给你 ComboBox :

    var names = Enum.GetNames( typeof(Protocol) );
    
        2
  •  -1
  •   epitka    15 年前

    不知道WPF,但在WebForms中(因为我使用MVP),我将列表>绑定到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);
            }
        }