在具有本地化名称的WPF ComboxBox中枚举

jue*_*n d 15 c# wpf enums localization mvvm

我有一个列出Enum的ComboBox.

enum StatusEnum {
    Open = 1, Closed = 2, InProgress = 3
}

<ComboBox ItemsSource="{Binding StatusList}"
          SelectedItem="{Binding SelectedStatus}" />
Run Code Online (Sandbox Code Playgroud)

我想用英语显示枚举值的本地化名称

Open
Closed
In Progress
Run Code Online (Sandbox Code Playgroud)

还有德语(以及将来的其他语言)

Offen
Geschlossen
In Arbeit
Run Code Online (Sandbox Code Playgroud)

在我的ViewModel中使用

public IEnumerable<StatusEnum> StatusList 
{
    get 
    {
        return Enum.GetValues(typeof(StatusEnum)).Cast<StatusEnum>();
    }
}
Run Code Online (Sandbox Code Playgroud)

只获取代码中枚举的名称而不是翻译的名称.

我有一般的本地化,可以使用ie访问它们

Resources.Strings.InProgress
Run Code Online (Sandbox Code Playgroud)

这让我获得了当前语言的翻译.

如何自动绑定本地化?

Yoh*_*all 19

这是一个简单Enum的翻译字符串转换器的例子.

public sealed class EnumToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
        { return null; }

        return Resources.ResourceManager.GetString(value.ToString());
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string str = (string)value;

        foreach (object enumValue in Enum.GetValues(targetType))
        {
            if (str == Resources.ResourceManager.GetString(enumValue.ToString()))
            { return enumValue; }
        }

        throw new ArgumentException(null, "value");
    }
}
Run Code Online (Sandbox Code Playgroud)

你还需要一个MarkupExtension能提供价值的东西:

public sealed class EnumerateExtension : MarkupExtension
{
    public Type Type { get; set; }

    public EnumerateExtension(Type type)
    {
        this.Type = type;
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        string[] names = Enum.GetNames(Type);
        string[] values = new string[names.Length];

        for (int i = 0; i < names.Length; i++)
        { values[i] = Resources.ResourceManager.GetString(names[i]); }

        return values;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

<ComboBox ItemsSource="{local:Enumerate {x:Type local:StatusEnum}}"
          SelectedItem="{Binding SelectedStatus, Converter={StaticResource EnumToStringConverter}}" />
Run Code Online (Sandbox Code Playgroud)

编辑:您可以制作更复杂的值转换器和标记扩展.在EnumToStringConverter可以使用DescriptionAttribute的,以获得翻译的字符串.并且EnumerateExtension可以使用TypeConverter.GetStandardValues()和转换器.这允许获得指定类型的标准值(不仅Enum是s),并根据转换器将它们转换为字符串或其他类型.

例:

<ComboBox ItemsSource="{local:Enumerate {x:Type sg:CultureInfo}, Converter={StaticResource CultureToNameConverter}}"
          SelectedItem="{Binding SelectedCulture, Converter={StaticResource CultureToNameConverter}}" />
Run Code Online (Sandbox Code Playgroud)

编辑:上面描述的更复杂的解决方案现在发布在GitHub上.