WPF 把枚举类型绑定到ComboBox 示例 1

public class Cls_EnumHandle
{
    public string GetDescription(Enum value)
    {
        if (value == null) throw new ArgumentNullException("value");
        string description = value.ToString();
        FieldInfo fieldInfo = value.GetType().GetField(description);
        EnumDescriptionAttribute[] attr = (EnumDescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(EnumDescriptionAttribute), false);
        if (attr != null && attr.Length > 0)
        {
            description = attr[0].Description;
        }
        return description;
    }
    public IList ToList(Type type)
    {
        if (type == null) throw new ArgumentNullException("type");
        if (!type.IsEnum) throw new ArgumentException("Type provided must be an Enum.", "type");
        ArrayList list = new ArrayList();
        Array array = Enum.GetValues(type);
        foreach (Enum value in array)
        {
            list.Add(new KeyValuePair<Enum,string>(value,GetDescription(value)));
        }
        return list;
    }
}
[AttributeUsage(AttributeTargets.Enum|AttributeTargets.Field,AllowMultiple=false)]
public class EnumDescriptionAttribute : Attribute
{
    private string description;
    public string Description
    {
        get
        {
            return this.description;
        }
    }
    public EnumDescriptionAttribute(string description) : base()
    {
        this.description = description;
    }
}
/// <summary>
/// 字体意义
/// </summary>
enum FontMean
{
    /// <summary>
    /// 正文
    /// </summary>
    [EnumDescription("正文")]
    Main,
    /// <summary>
    /// 批注
    /// </summary>
    [EnumDescription("批注")]
    Postil,
    /// <summary>
    /// 双列小字
    /// </summary>
    [EnumDescription("双列小字")]
    Double,
    /// <summary>
    /// 三列小字
    /// </summary>
    [EnumDescription("三列小字")]
    Three,
    /// <summary>
    /// 四列小字
    /// </summary>
    [EnumDescription("四列小字")]
    Four,
    /// <summary>
    /// 五列小字
    /// </summary>
    [EnumDescription("五列小字")]
    Five,
    /// <summary>
    /// 插入字
    /// </summary>
    [EnumDescription("插入字")]
    Insert,
    /// <summary>
    /// 其它
    /// </summary>
    [EnumDescription("其它")]
    Other
}
cbxFontType.DataSource = new Cls_EnumHandle().ToList(typeof(FontMean));
cbxFontType.DisplayMember = "Value";
cbxFontType.ValueMember = "Key";


知识共享许可协议
《WPF 把枚举类型绑定到ComboBox 示例 1》常伟华 创作。
采用 知识共享 署名-相同方式共享 3.0 中国大陆 许可协议进行许可。
  • 多说评论
  • 签名
  • 新浪微博
  • 默认评论
  • Tab Header 5

0 条评论 / 点击此处发表评论

Tab Content 5

开发技术


开发平台和工具

sitemap     153.16ms