如何绑定一个枚举组合框
我会绑定在ComboBox控件的枚举值
I would bind the values of an enumeration with a combobox control.
我写这段代码:
cboPriorLogicalOperator.DataSource = Enum.GetValues(typeof(MyEnum))
.Cast<MyEnum>()
.Select(p => new { Key = (int)p, Value = p.ToString() })
.ToList();
myComboBox.DisplayMember = "Value";
myComboBox.ValueMember = "Key";
它工作得很好,但我不知道是否有更简单的方法。
It works well but I wonder if there is a simpler way.
我觉得你的代码是美丽的!
I think your code is beautiful!
唯一的改进是将代码放在一个扩展方法的
The only improvement would be to place the code in an Extension Method.
编辑:
当我想想,你想要做的就是使用枚举
中的定义,而不是枚举,这是扩展方法所需的实例。
When I think about it, what you want to do is to use the Enum
as in the definition and not an instance of the enum, which is required by extensions methods.
我发现这个问题,该解决它真的很好:
I found this question, which solves it really nicely:
public class SelectList
{
// Normal SelectList properties/methods go here
public static Of<T>()
{
Type t = typeof(T);
if (t.IsEnum)
{
var values = from Enum e in Enum.GetValues(type)
select new { ID = e, Name = e.ToString() };
return new SelectList(values, "Id", "Name");
}
return null;
}
}
// called with
var list = SelectList.Of<Things>();
只有你可能要返回一个词典< INT,串> 。code>,而不是
的SelectList
,但你的想法
Only you might want to return a Dictionary<int, string>
and not a SelectList
, but you get the idea.
EDIT2:
下面,我们一起去覆盖你正在看的情况下的代码示例。
Here we go with a code example that covers the case you are looking at.
public class EnumList
{
public static IEnumerable<KeyValuePair<T, string>> Of<T>()
{
return Enum.GetValues(typeof (T))
.Cast<T>()
.Select(p => new KeyValuePair<T, string>(p, p.ToString()))
.ToList();
}
}
还是这个版本或许,这里的关键是 INT
public class EnumList
{
public static IEnumerable<KeyValuePair<int, string>> Of<T>()
{
return Enum.GetValues(typeof (T))
.Cast<T>()
.Select(p => new KeyValuePair<int, string>(Convert.ToInt32(p), p.ToString()))
.ToList();
}
}