繁体   English   中英

将枚举绑定到组合框,再加上一个自定义选项

[英]bind enum to combobox plus one custom choice

我遵循了这里给出的建议: 如何使用C#中的空字段将Enum绑定到combobox,但这给了我一些不可用的内容:

结果

不是我想看到的...这是我以前绑定的代码:

comboBox2.DataSource = GetDataSource(typeof (MessageLevel), true);

这是背景:

public enum MessageLevel
{
    [Description("Information")]
    Information,
    [Description("Warning")]
    Warning,
    [Description("Error")]
    Error
}
----
public static string GetEnumDescription(string value)
{
    Type type = typeof(MessageLevel);
    var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();

    if (name == null)
    {
        return string.Empty;
    }
    var field = type.GetField(name);
    var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
    return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
}

public static List<object> GetDataSource(Type type, bool fillEmptyField = false)
{
    if (type.IsEnum)
    {
        var data = Enum.GetValues(type).Cast<Enum>()
                   .Select(E => new { Key = (object)Convert.ToInt16(E), Value = GetEnumDescription(E.ToString()) })
                   .ToList<object>();

        var emptyObject = new { Key = default(object), Value = "" };

        if (fillEmptyField)
        {
            data.Insert(0, emptyObject); // insert the empty field into the combobox
        }
        return data;
    }
    return null;
}

如何进行正确的绑定并添加一个空条目?

因此,解决方案是还要在ComboBox上设置DisplayMemberValueMember属性,以便它将知道如何处理KeyValue属性。

comboBox2.DataSource = GetDataSource(typeof (MessageLevel), true);
comboBox2.DisplayMember = "Value";
comboBox2.ValueMember = "Key";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM