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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With