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

Den*_*ail 5 c# xaml windows-phone-7

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

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

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

this.listBox1.ItemSource = Enum<Colors>.GetNames();
Run Code Online (Sandbox Code Playgroud)