WPF - 在组合框中更改枚举的字符串值

Yon*_*Nir 4 c# wpf enums combobox

我有一个枚举,我在组合框中使用它的值作为选择.

枚举是这样的:

public enum TimeSizeEnum
{
    TENTHSECONDS,
    SECONDS,
    MINUTES,
    HOURS
}
Run Code Online (Sandbox Code Playgroud)

我将值绑定到组合框的方式:

<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));
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望而不是TENTHSECONDS,我会看到"Tenth of a second"或代替SECONDS,我会看到"Seconds".

我怎样才能做到这一点?值转换器是最好的方法吗?但那意味着我需要对我想要的字符串进行硬编码?

Chr*_*tle 7

我建议使用DescriptionAttribute:

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

    [Description("Seconds")]
    SECONDS,

    [Description("Minutes")]
    MINUTES,

    [Description("Hours")]
    HOURS
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以检查enum您在a中传递的值ValueConverter,从属性中读取描述,并显示:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

要将值转换器应用于每个枚举值,您需要更改组合框ItemTemplate以包含值转换器:

<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>
Run Code Online (Sandbox Code Playgroud)