XAML中的枚举转换器

时间:2014-05-30 10:08:58

标签: c# xaml windows-phone-8 enums windows-phone-8.1

我有一个枚举

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

这是ItemsSource的代码

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

我想用多语言转换器将它绑定到我的ComboBox

Maybe multilanguages converter

enter image description here

我该怎么做?

1 个答案:

答案 0 :(得分:5)

我对本地化没有太多帮助,但我可能会使用自定义转换器来解决这个问题。 (当您使用ComboBox时,我假设您正在使用Windows Phone Store应用程序,而不是Windows Phone Silverlight应用程序。)

1:将枚举值的翻译添加到不同的Resources.resw文件(例如美国英语/Strings/en-US/Resources.resw,请参阅http://code.msdn.microsoft.com/windowsapps/Application-resources-and-cd0c6eaa),该表格如下所示:

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

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:将其添加到App.xaml中的资源词典中,例如:

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

4:在ComboBox中,创建一个使用此转换器的项目模板:

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

可能有一种更简单的方法,但这是我现在能想到的最好的方法。

相关问题