简体   繁体   English

XAML中的枚举转换器

[英]Enum converter in XAML

I have an enum 我有一个枚举

public enum AccountType
{
    Cash,
    PrepaidCard,
    CreditCard,
    Project
}

And this is code for ItemsSource 这是ItemsSource的代码

typeComboxBox.ItemsSource = Enum.GetValues(typeof(AccountType)).Cast<AccountType>();

And I want binding it to my ComboBox like this with multilanguage converter 我想使用多语言转换器将其绑定到我的ComboBox

也许多语言转换器

在此处输入图片说明

How can I do that? 我怎样才能做到这一点?

I haven't worked a lot with localization, but I would probably solve this using a custom converter. 我在本地化方面工作不多,但我可能会使用自定义转换器解决此问题。 (As you use a ComboBox I assume you are doing a Windows Phone Store app, and not a Windows Phone Silverlight app). (当您使用ComboBox我假设您正在使用Windows Phone Store应用程序,而不是Windows Phone Silverlight应用程序)。

1: Add translations for the enum values to the different Resources.resw files (eg /Strings/en-US/Resources.resw for US English, see http://code.msdn.microsoft.com/windowsapps/Application-resources-and-cd0c6eaa ), the table will look something like: 1:将枚举值的翻译添加到不同的Resources.resw文件中(例如,针对美国英语的/Strings/en-US/Resources.resw ,请参见http://code.msdn.microsoft.com/windowsapps/Application-resources-和-cd0c6eaa ),该表将类似于:

|-------------|--------------|--------------|
| Name        | Value        | Comment      |
|-------------|--------------|--------------|
| Cash        | Cash         |              |
| PrepaidCard | Prepaid card |              |
| CreditCard  | Credit card  |              |
| Project     | Project      |              |

2: Then create a custom converter: 2:然后创建一个自定义转换器:

public class LocalizationConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return ResourceLoader.GetForCurrentView().GetString(value.ToString());
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

3: Add this to the resource Dictionary in App.xaml for example: 3:例如,将其添加到App.xaml的资源Dictionary中:

<Application.Resources>
    <local:LocalizationConverter x:Key="LocalizationConverter" />
</Application.Resources>

4: In the ComboBox , create an item template which uses this converter: 4:在ComboBox ,创建一个使用此转换器的项目模板:

<ComboBox x:Name="typeComboxBox">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Converter={StaticResource LocalizationConverter}}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

There might be an easier way, but this is the best one I can Think of right now. 也许有一种更简单的方法,但这是我现在能想到的最好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM