将枚举绑定到组合框以及一个自定义选项

时间:2015-09-25 11:13:21

标签: c# winforms combobox enums

我遵循了这里给出的建议:How to bind Enum to combobox with empty field in C#但它给了我一些无法使用的内容:

Result

我希望看到的内容......以下是我用来绑定的代码:

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;
}

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

1 个答案:

答案 0 :(得分:1)

因此解决方案是在ComboBox上设置KeyValue属性,以便它知道如何处理comboBox2.DataSource = GetDataSource(typeof (MessageLevel), true); comboBox2.DisplayMember = "Value"; comboBox2.ValueMember = "Key"; 和{{1}}属性。

{{1}}