ListView and enums
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
?
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 :-)
精彩评论