How do I bind an enum to my listbox?

Deadly 提交于 2019-12-05 00:11:28

问题


I have a Silverlight (WP7) project and would like to bind an enum to a listbox. This is an enum with custom values, sitting in a class library. How do I do this?


回答1:


In Silverlight(WP7), Enum.GetNames() method is not available. You can use the following

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>();
    }
}

The static method will returns enumerable string collection. You can bind that to a listbox's itemssource. Like

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



回答2:


Use a converter to do this. Refer to http://geekswithblogs.net/cskardon/archive/2008/10/16/databinding-an-enum-in-wpf.aspx.




回答3:


Convert the enum to a list (or similar) - as per How do I convert an enum to a list in C#?

then bind to the converted list.



来源:https://stackoverflow.com/questions/3935953/how-do-i-bind-an-enum-to-my-listbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!