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

时间:2014-06-21 17:56:43

标签: c# wpf combobox enums

我有一个枚举,我将其值用作组合框中的选项。

枚举是这样的:

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

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

<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));
    }
}

我想要而不是TENTHSECONDS,我会看到"Tenth of a second"SECONDS,而不是"Seconds",我会看到{{1}}。

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

2 个答案:

答案 0 :(得分:6)

我建议使用DescriptionAttribute

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

    [Description("Seconds")]
    SECONDS,

    [Description("Minutes")]
    MINUTES,

    [Description("Hours")]
    HOURS
}

然后,您可以检查enum中传递的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();
    }
}

要将值转换器应用于每个枚举值,您需要更改组合框的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>

答案 1 :(得分:3)

您可以将属性放在枚举成员上,如

public enum TimeSizeEnum
{
    [Description("Tenth of a second")]
    TENTHSECONDS,
    [Description("Seconds")]
    SECONDS,
}

然后你可以编写一个转换器,它从传递的值中读取并返回这些属性,即你可以编写的IValueConveter的Convert方法

var enumtype = typeof(TimeSizeEnum);
var memInfo = enumtype.GetMember(value.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),
    false);
var description = ((DescriptionAttribute)attributes[0]).Description;

return description
相关问题