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?
3 Answers
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();
5 Comments
K2so
Then, the next question is, how do you assign, with binding, the selected enum value back to a property in the viewmodel? I've been looking around for answers, but couldn't find any resource, any direction pointing is appreciated. thanks.
Prince Ashitaka
@K2so You can have a property in the view model bound to the
SelectedItem property of the ListBox. check the following sample that could help you. sites.google.com/site/html5tutorials/BindingEnum.zipShawn Wildermuth
Mind if I borrow this code and attribute to you in my PhoneyTools project so people can use it? phoney.codeplex.com?
Prince Ashitaka
@ Shawn Wildermuth I'm honoured :) I'm a big fan of your blogs :)
Robert Kozak
What about [Description] attribute? Often it is helpful to use this when Enums need a better string representation. You are not handling that case here.
Use a converter to do this. Refer to http://geekswithblogs.net/cskardon/archive/2008/10/16/databinding-an-enum-in-wpf.aspx.
Comments
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.