Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converter to show description of an enum, and convert back to enum value on selecting an item from combo box in wpf

I am using an enum to enlist values in my combobox. I want to write a converter that would show the "description" of the selected enum value. And, when selected, it would return the enum value.

Most of the converters online have not implemented the ConvertBack() method (which is why I am posting here).

like image 630
aromore Avatar asked Nov 29 '13 17:11

aromore


1 Answers

Here is ConvertBack method:

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    return value;
}

Full Converter Code:

public class EnumConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null) return DependencyProperty.UnsetValue;

        return GetDescription((Enum)value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value;
    }

    public static string GetDescription(Enum en)
    {
        Type type = en.GetType();
        MemberInfo[] memInfo = type.GetMember(en.ToString());
        if (memInfo != null && memInfo.Length > 0)
        {
            object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attrs != null && attrs.Length > 0)
            {
                return ((DescriptionAttribute)attrs[0]).Description;
            }
        }
        return en.ToString();
    }
}

EDIT

Here is my ComboBox XAML:

<ComboBox ItemsSource="{Binding SampleValues}" 
          SelectedItem="{Binding SelectedValue, Converter={StaticResource enumConverter}}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=., Converter={StaticResource enumConverter}}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
like image 167
Suresh Avatar answered Sep 28 '22 03:09

Suresh