【问题标题】:bind enum to combobox plus one custom choice将枚举绑定到组合框以及一个自定义选项
【发布时间】:2015-12-23 05:04:50
【问题描述】:

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

不是我想看到的......这是我用来绑定的代码:

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

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

【问题讨论】:

  • 尝试设置DisplayMemberPath="Value"SelectedValuePath="Key"
  • @Michael 因为它是 winform(我是过失,我一开始没有标记它)它是 DisplayMember 和 ValueMember。如果你想要一些代表...... :)
  • GetEnumDescription() 的目的是什么?它似乎试图访问枚举值中的属性。
  • @Ian 是的,我已经粘贴了一个旧版本的枚举,它现在已经修复了
  • @Thomas 谢谢,我以为是WPF

标签: c# winforms combobox enums


【解决方案1】:

所以解决方案是在 ComboBox 上同时设置 DisplayMemberValueMember 属性,这样它就会知道如何处理 KeyValue 属性。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 2018-11-12
    • 2020-02-07
    相关资源
    最近更新 更多