I have a simple ComboBox that has some simple values. I’m trying to do 2 way binding with an enum property on my model.
<ComboBox d:LayoutOverrides="Height" Grid.Column="1" SelectedItem="{Binding SortType, Converter={StaticResource sortSelect}, Mode=TwoWay}">
<ListBoxItem Content="Ascending" Tag="Ascending"/>
<ListBoxItem Content="Descending" Tag="Descending"/>
<ListBoxItem Content="Absolute Ascending" Tag="AbsoluteAscending"/>
<ListBoxItem Content="Absolute Descending" Tag="AbsoluteDescending" />
</ComboBox>
Here is my ValueConverter
public class RdiSortMatchConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var val = (RdiSort) value;
switch (val)
{
case RdiSort.Ascending:
return "Ascending";
case RdiSort.Descending:
return "Descending";
case RdiSort.AbsoluteAscending:
return "Absolute Ascending";
case RdiSort.AbsoluteDescending:
return "Absolute Descending";
default:
throw new ArgumentOutOfRangeException();
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return (RdiSort) Enum.Parse(typeof (RdiSort), (string) ((ListBoxItem) value).Tag);
}
}
The ConvertBack method works fine, and updates my model based on the Tag value in the ListBoxItem, but I cant get the initial Enum value to select the correct ListBoxItem
whats the best way about achieving this, or is there a better way of binding t Enums (take into consideration that I need custom descriptions for each Enum value.
You can do it like this. First add a description for each of your Enum values
Then use an ObjectDataProvider for your ComboBox
Use the RdiSortValues provider in your ComboBox and create a DataTemplate with a TextBlock and a Converter to see the Description instead of the Enum value.
And finally the converter. There is no need to ConvertBack since the converter is only used in the TextBlock for displaying.