Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - Change string values of enum in combo box

I've got an enum which I use its values as choices in a combo box.

The enum is this:

public enum TimeSizeEnum
{
    TENTHSECONDS,
    SECONDS,
    MINUTES,
    HOURS
}

The way I'm binding the values to the combo box:

<ComboBox Grid.Row="4" Grid.Column="1" ItemsSource="{Binding Path=TimeSizeItemsSource, Converter={StaticResource TimerSizeConverter}}" SelectedItem="{Binding Path=TimeSize, Mode=TwoWay}" SelectedIndex="0" Margin="5" MinWidth="100"></ComboBox>

public string[] TimeSizeItemsSource
{
    get
    {
        return Enum.GetNames(typeof(TimeSizeEnum));
    }
}

I want that instead of TENTHSECONDS, I'll see "Tenth of a second" or instead of SECONDS, I'll see "Seconds".

How can I achieve that? Is a value converter the best way to do it? But then it means I need to hard-code the strings I want?

like image 777
Yonatan Nir Avatar asked Dec 25 '22 07:12

Yonatan Nir


1 Answers

I'd recommend using the DescriptionAttribute:

public enum TimeSizeEnum
{
    [Description("Tenths of a second")]
    TENTHSECONDS,

    [Description("Seconds")]
    SECONDS,

    [Description("Minutes")]
    MINUTES,

    [Description("Hours")]
    HOURS
}

You can then examine the enum value you're passed in a ValueConverter, read the description from the attribute, and display that:

public class TimeSizeEnumDescriptionValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var type = typeof(TimeSizeEnum);
        var name = Enum.GetName(type, value);
        FieldInfo fi = type.GetField(name);
        var descriptionAttrib = (DescriptionAttribute)
            Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));

        return descriptionAttrib.Description;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

To apply the value converter to each enum value, you need to change the combo box's ItemTemplate to include the value converter:

<Window.Resources>
    <test:TimeSizeEnumDescriptionValueConverter x:Key="converter" />
</Window.Resources>

<!-- ... -->

<ComboBox ItemsSource="{Binding TimeSizeItemsSource}" >
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <ContentPresenter
                Content="{Binding Converter={StaticResource converter}}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
like image 152
Chris Mantle Avatar answered Jan 07 '23 09:01

Chris Mantle