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.

Share:
11,572
DenaliHardtail
Author by

DenaliHardtail

Updated on June 04, 2022

Comments

  • DenaliHardtail
    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?

  • K2so
    K2so over 13 years
    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
    Prince Ashitaka over 13 years
    @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.zip
  • Shawn Wildermuth
    Shawn Wildermuth about 13 years
    Mind if I borrow this code and attribute to you in my PhoneyTools project so people can use it? phoney.codeplex.com?
  • Prince Ashitaka
    Prince Ashitaka about 13 years
    @ Shawn Wildermuth I'm honoured :) I'm a big fan of your blogs :)
  • Robert Kozak
    Robert Kozak about 13 years
    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.