使用索引键将字符串从.resx ResourceDictionary绑定到TextBlock.Text [英] Bind string from .resx ResourceDictionary to TextBlock.Text using index key

查看:78
本文介绍了使用索引键将字符串从.resx ResourceDictionary绑定到TextBlock.Text的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Properties/Resources.resx文件进行本地化,以不同的语言显示我的观点.

i'm trying to get my view in different languages, using Properties/Resources.resx file for localization.

我的模型如下所示:

class City 
{
    public int Id { get; set; }
    public string LocalizationKey { get; set; }
}

ViewModel:

The ViewModel:

class ViewModel
{
    public ObservableCollection<City> Cities { get; set; }
}

在我的视图上,我有以下代码:

And on my View, i've the following code:

<ItemsControl ItemsSource="{Binding Cities}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding LocalizationKey}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

当我只想从字典中获取我的字符串键的值时,只有一项没有项目集合,它可以使用以下代码正常工作:

When i want to get the value of my string key from the dictionary for only one item without Items Collection it works correctly by using the following code:

<TextBlock Text="{x:Static properties:Resources.MyStringKey}" />

问题是当上面的代码与ItemsControl一起使用时,其中的键是未知的!是否可以通过使用LocalizationKey作为索引来访问字典值的任何方法?

The problem is when using the code above with an ItemsControl where the keys are unknowns! Is there any way to access to the dictionary values by using the LocalizationKey as an index?

推荐答案

经过数小时的网络搜索,我终于找到了使用转换器的解决方案,它可能不是解决问题的最佳方法,但至少可以做到我想要:

After hours of web searching, i finally found a solution by using a converter, it may not the best practices to solve the problem but at least it does exactly what i want:

我的转换器:

public class LocalizationConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var key = value as string;
        if (!string.IsNullOrEmpty(key))
        {
            string dictionaryValue = Resources.ResourceManager.GetString(key);
            return dictionaryValue ?? key;
        }
        return value;
    }

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

和XAML代码:

<TextBlock Text="{Binding LocalizationId, Converter={StaticResource LocalizationConverter}}" />

谢谢.

这篇关于使用索引键将字符串从.resx ResourceDictionary绑定到TextBlock.Text的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆