2015-09-25 135 views
1

我已經按照這裏給出的建議是: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; 
} 

如何進行正確的綁定並添加一個空條目?

+0

嘗試設置'的DisplayMemberPath =「值」'和'SelectedValuePath =「密鑰」' – Michael

+0

@邁克爾,因爲它是WinForm的(過失,我並沒有在第一個標籤的話)它的DisplayMember和ValueMember。如果你想要一些代表... :) –

+0

GetEnumDescription()的目的是什麼?它似乎嘗試訪問枚舉值中的屬性。 – Ian

回答

1

所以解決的辦法就是也設置組合框DisplayMemberValueMember性質,所以它會知道如何處理KeyValue性能。

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