2

I often have to deal with lists in the user interface that translate to an enum value in the 'ViewModel'. I know that I can directly bind ListView.ItemSource to an enum via ObjectDataProvider that provides the enum item names, but often this is not optimal, because the visual representation of a list item should differ from the enum item name.

Also, items from the enum sometimes need to be left out in the visual list representation.

so for example:

    enum WhatIWantIsA        {
        NiceHouse,
        FastCar,
        Nothing // omitted in the view
    }

Should translate to a list with the items:

    A nice house
    A fast car

So my question is: How do you deal with lists, that have a predefined number of entries and translate to an enum in the ViewModel?

thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110
  • 1
    This answer may help: http://stackoverflow.com/questions/5350684/adding-enum-to-combobox/5350792#5350792 personally I would go with the solution I suggested - this would fit with a view model quite nicely. – Adam Houldsworth Apr 13 '11 at 07:57
  • sorry, that's not what I meant. I edited my question to make it clearer – thumbmunkeys Apr 13 '11 at 08:06
  • 1
    actually I think it is, the point is that you need to define the list of items and associate them with an enum value. The class I described in that answer features a `Name` and `Value`, the name is something you define. Alternatively, decorate the enum with attributes and have some generic code that returns a custom type for you. – Adam Houldsworth Apr 13 '11 at 08:13
  • thanks adam! right, it actually is what i meant. And you can even omit enum items with that solution – thumbmunkeys Apr 13 '11 at 08:43

1 Answers1

3

You can use an IValueConverter on your binding to translate the enum to a readable form:

public class MyEnumValueConverter : IValueConverter
{
    public object Convert(object value, Type type, ...)
    {
        var enumVal = (WhatIWantIsA)value;
        switch (enumVal)
        {
            case "NiceHouse": return "A nice house";
            case "FastCar": return "A fast car";
            default: return "Unknown Value"; //or throw exception    
        }
    }
    public object ConvertBack(object value, Type type, ...)
    {
        return value; //probably don't need to implement this
    }
}

Use this on your binding:

<Resources>
    <local:MyEnumValueConverter x:Key="myEnumConverter"/>
</Resources>
<ListView ItemsSource="{Binding Converter={StaticResource myEnumConverter}}"/>

This way, your ViewModel can keep working with the enum, and the user sees a decent value.

Hope this helps...

Edit: updated the example to use Enum provided in the question :-)

RoelF
  • 7,483
  • 5
  • 44
  • 67