如何将枚举绑定到组合框

Hom*_*mam 39 c# winforms

我会使用组合框控件绑定枚举的值.

我写了这段代码:

cboPriorLogicalOperator.DataSource = Enum.GetValues(typeof(MyEnum))
    .Cast<MyEnum>()
    .Select(p => new { Key = (int)p, Value = p.ToString() })
    .ToList();

myComboBox.DisplayMember = "Value";
myComboBox.ValueMember = "Key";
Run Code Online (Sandbox Code Playgroud)

它运作良好,但我想知道是否有一个更简单的方法.

Mik*_*erg 25

我觉得你的代码很漂亮!

唯一的改进是将代码放在扩展方法中.

编辑:

当我考虑它时,你想要做的是使用Enum定义中的as而不是扩展方法所需的枚举实例.

我发现了这个问题,很好地解决了这个问题:

public class SelectList
{
    // Normal SelectList properties/methods go here

    public static SelectList Of<T>()
    {
       Type t = typeof(T);
       if (t.IsEnum)
       {
           var values = from Enum e in Enum.GetValues(t)
                        select new { ID = e, Name = e.ToString() };
           return new SelectList(values, "Id", "Name");
       }
       return null;
    }
}

// called with 
var list = SelectList.Of<Things>();
Run Code Online (Sandbox Code Playgroud)

只有你可能想要返回a Dictionary<int, string>而不是a SelectList,但你明白了.

EDIT2:

在这里,我们将使用代码示例来介绍您正在查看的案例.

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

或许这个版本,其中关键是 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();
    }
}
Run Code Online (Sandbox Code Playgroud)


Jac*_*nev 6

为什么不使用:

myComboBox.DataSource  = Enum.GetValues(typeof(MyEnum))
Run Code Online (Sandbox Code Playgroud)