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?
            Asked
            
        
        
            Active
            
        
            Viewed 1.2k times
        
    5
            
            
        - 
                    1possible duplicate of [Databinding an enum property to a ComboBox in WPF](http://stackoverflow.com/questions/58743/databinding-an-enum-property-to-a-combobox-in-wpf) – Andrey Oct 14 '10 at 17:46
3 Answers
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();
 
    
    
        Prince Ashitaka
        
- 8,623
- 12
- 48
- 71
- 
                    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 Nov 22 '10 at 04:54
- 
                    1@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. https://sites.google.com/site/html5tutorials/BindingEnum.zip – Prince Ashitaka Nov 22 '10 at 05:27
- 
                    Mind if I borrow this code and attribute to you in my PhoneyTools project so people can use it? http://phoney.codeplex.com? – Shawn Wildermuth Mar 24 '11 at 07:15
- 
                    @ Shawn Wildermuth I'm honoured :) I'm a big fan of your blogs :) – Prince Ashitaka Mar 24 '11 at 16:35
- 
                    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. – Robert Kozak Mar 29 '11 at 15:32
1
            
            
        Use a converter to do this. Refer to http://geekswithblogs.net/cskardon/archive/2008/10/16/databinding-an-enum-in-wpf.aspx.
 
    
    
        Ray Zhang
        
- 91
- 1
- 3
-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.
 
    
    
        Community
        
- 1
- 1
 
    
    
        Matt Lacey
        
- 65,560
- 11
- 91
- 143
