1
我已经按照这里给出的建议是: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 =“值”'和'SelectedValuePath =“密钥”' – Michael
@迈克尔,因为它是WinForm的(过失,我并没有在第一个标签的话)它的DisplayMember和ValueMember。如果你想要一些代表... :) –
GetEnumDescription()的目的是什么?它似乎尝试访问枚举值中的属性。 – Ian