How do I bind an enum to my listbox?
11,572
Solution 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();
Solution 2
Use a converter to do this. Refer to http://geekswithblogs.net/cskardon/archive/2008/10/16/databinding-an-enum-in-wpf.aspx.
Author by
DenaliHardtail
Updated on June 04, 2022Comments
-
DenaliHardtail almost 2 years
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?
-
Andrey over 13 yearspossible duplicate of Databinding an enum property to a ComboBox in WPF
-
-
K2so over 13 yearsThen, 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 over 13 years@K2so You can have a property in the view model bound to the
SelectedItem
property of theListBox
. check the following sample that could help you. sites.google.com/site/html5tutorials/BindingEnum.zip -
Shawn Wildermuth about 13 yearsMind if I borrow this code and attribute to you in my PhoneyTools project so people can use it? phoney.codeplex.com?
-
Prince Ashitaka about 13 years@ Shawn Wildermuth I'm honoured :) I'm a big fan of your blogs :)
-
Robert Kozak about 13 yearsWhat about [Description] attribute? Often it is helpful to use this when Enums need a better string representation. You are not handling that case here.