如何绑定一个枚举组合框 [英] How to bind an enumeration to combobox

查看:135
本文介绍了如何绑定一个枚举组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会绑定在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,串> ,而不是的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();
    }
}

这篇关于如何绑定一个枚举组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆