【问题标题】:Enum converter in XAMLXAML 中的枚举转换器
【发布时间】:2014-05-30 10:08:57
【问题描述】:

我有一个枚举

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

这是 ItemsSource 的代码

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

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

我该怎么做?

【问题讨论】:

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


【解决方案1】:

我在本地化方面工作不多,但我可能会使用自定义转换器来解决这个问题。 (当您使用 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>

可能有更简单的方法,但这是我目前能想到的最好的方法。

【讨论】:

    猜你喜欢
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 2020-08-21
    • 2021-01-04
    • 2023-02-21
    相关资源
    最近更新 更多