将.resx ResourceDictionary中的字符串绑定到TextBlock.使用索引键的文本

本文关键字:索引 文本 TextBlock 绑定 ResourceDictionary resx 字符串 | 更新日期: 2023-09-27 18:05:34

我正在尝试使用属性/资源以不同的语言获取我的视图。用于本地化的Resx文件。

我的模型如下所示:

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

ViewModel:

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

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

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

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

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

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

将.resx ResourceDictionary中的字符串绑定到TextBlock.使用索引键的文本

你能不能这样做:

public class City
{
    public int Id { get; set; }
    public string LocalizationKey { get; set; }
    public City(string englishName)
    {
        LocalizationKey = Properties.Resources.ResourceManager.GetString(englishName);
    }
}

我不确定这是最佳实践;但这是我第一个想到的

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

My Converter:

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}}" />

谢谢。