如何将枚举绑定到列表框?

时间:2010-10-14 17:43:03

标签: c# xaml windows-phone-7

我有一个Silverlight(WP7)项目,并希望将枚举绑定到列表框。这是一个包含自定义值的枚举,位于类库中。我该怎么做?

3 个答案:

答案 0 :(得分:11)

在Silverlight(WP7)中,Enum.GetNames()方法不可用。您可以使用以下

public class Enum<T>
{
    public static IEnumerable<string> GetNames()
    {
        var type = typeof(T);
        if (!type.IsEnum)
            throw new ArgumentException("Type '" + type.Name + "' is not an enum");

        return (
          from field in type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)
          where field.IsLiteral
          select field.Name).ToList<string>();
    }
}

静态方法将返回可枚举的字符串集合。您可以将其绑定到列表框的itemssource。像

this.listBox1.ItemSource = Enum<Colors>.GetNames();

答案 1 :(得分:1)

答案 2 :(得分:-1)

根据How do I convert an enum to a list in C#?

将枚举转换为列表(或类似)

然后绑定到转换后的列表。