5

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

3 Answers 3

11

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();
Sign up to request clarification or add additional context in comments.

5 Comments

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.
@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
Mind if I borrow this code and attribute to you in my PhoneyTools project so people can use it? phoney.codeplex.com?
@ Shawn Wildermuth I'm honoured :) I'm a big fan of your blogs :)
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.
1

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

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.