从语言文件绑定动态值的正确方法是什么?

本文关键字:方法 是什么 语言 文件 绑定 动态 | 更新日期: 2023-09-27 18:02:55

我有一个视图模型,它在我的语言资源文件中有一个条目名称。
我试图将此值直接绑定到XAML中TextBlock的x:Uid属性,但得到了XAML错误。

为了绕过这个限制,我考虑更改属性以返回语言文件的值,但担心这样做可能不是一个有效的MVVM解决方案。
我还想过创建一个转换器来设置文本。

行不通的方法:

<StackPanel Orientation="Horizontal">
    <Image Margin="0,0,20,0" Source="{Binding IconPath}" />
    <TextBlock x:Uid="{Binding LanguageResourceName}" />
</StackPanel>

我要绑定的视图模型:

class Tab : ViewModelBase
{
    private string _IconPath,
        _LanguageResourceName;
    private ViewModelBase _ViewModel;
    /// <summary>
    /// The path to the icon to show on the tab.
    /// </summary>
    public string IconPath
    {
        get { return _IconPath; }
        set { SetProperty(ref _IconPath, value); }
    }
    /// <summary>
    /// The name of the entry in the language resource file to display on the tab.
    /// </summary>
    public string LanguageResourceName
    {
        get { return _LanguageResourceName; }
        set { SetProperty(ref _LanguageResourceName, value); }
    }
    /// <summary>
    /// The contents of the tab.
    /// </summary>
    public ViewModelBase ViewModel
    {
        get { return _ViewModel; }
        set { SetProperty(ref _ViewModel, value); }
    }
}

那么解决这个问题的正确方法是什么?

从语言文件绑定动态值的正确方法是什么?

转换器是最好的方法。点击这里查看我的回答。我已经复制了下面定义的Converter。

ResourceController是一个简单的控制器,它获得对ResourceLoader的引用并通过GetString(string resourceId)方法检索值。

public class ResourceTranslationConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var valString = value as string;
        // If what is being converted is a string, return the resource translation
        // Else return something else, such as the object itself
        return valString == null ? value : ResourceController.GetString(valString);
    }
    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

绑定工作如下:

<TextBlock Text="{Binding LanguageResourceName, Converter={StaticResource ResourceTranslationConverter}}" />

确保您已经定义了一个可访问的ResourceTranslationConverter。可能在Page.Resources或甚至在你的App.xaml(因为你应该只需要一个静态引用)。

希望这有助于和快乐的编码!