本地化windows phone 8应用程序-XAML ListView到Resources.resx键的动态绑定



对于windows phone 8应用程序,我使用Resource.resx显示单个TextBlock的随机文本的本地语言翻译,没有任何问题。

现在,我想对一个表中存储的大约100个类别名称做类似的事情。

我想将该表绑定到ListView

我应该使用Resource.resx文件中的100个类别名称中的每一个作为关键字吗?或者我应该像Category_1001一样命名密钥,而不是例如Breads,这样如果我需要将Breads更改为Bread,我就不必更改大量代码了?

问题:如果我要走第二条路线(Category_1001),有没有任何方法可以在XAML中以声明方式完成这一操作,或者我需要在XAML.cs中以编程方式完成这项操作?

如果有这么多相同类型的对象,我可以建议以下解决方案。

在*.resx文件中,您可以存储Category_XXXX密钥。之后,您可以创建枚举

public enum Category
{
    Bread = 1, // number here should correspond to the proper resource key
    Oil = 2,
    Potato = 3,
    Tomato = 4,
    ...
}

然后创建您的价值转换器

[ValueConversion(typeof(Category), typeof(String))]
public class CategoryConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        int category = (int)value;
        string res;
        try
        {
            res = Resources.ResourceManager.GetString(string.Format("Category_{0:d4}", (int)category));
        }
        catch(Exception e)
        {
           res = string.Format("Unable to obtain resource {0}: {1}", Category, e.Message);
        }
        return res;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
         throw new NotSupportedException();
    }
}

然后在你的*.xaml:中

<TextBlock Text="{Binding Path=Category, Converter={StaticResource MyCategoryConverter}}" />

您也可以提取该方法,以便在ViewModels中使用它。

最新更新