我有一个 View 模型,它具有我的语言资源文件中条目的名称。
我试图将此值直接绑定(bind)到我的 XAML 中 TextBlock
的 x:Uid 属性,但出现了 XAML 错误。
为了绕过这个限制,我考虑过更改属性以从语言文件返回值,但担心这样做可能不是有效的 MVVM 解决方案。
我还考虑过创建一个转换器来设置文本。
行不通的方式:
<StackPanel Orientation="Horizontal">
<Image Margin="0,0,20,0" Source="{Binding IconPath}" />
<TextBlock x:Uid="{Binding LanguageResourceName}" />
</StackPanel>
我要绑定(bind)的 View 模型:
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 是最好的方法。查看我的回答here快速解释。我已经复制了我在下面定义的转换器。
ResourceController
是一个简单的 Controller ,它获取对 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();
}
}
然后绑定(bind)的工作方式如下:
<TextBlock Text="{Binding LanguageResourceName, Converter={StaticResource ResourceTranslationConverter}}" />
确保您已经定义了一个可访问的 ResourceTranslationConverter
.可能在 Page.Resources
甚至在你的 App.xaml
(因为您应该只需要一个静态引用)。
希望这对您有所帮助,祝您编码愉快!
关于c# - 从语言文件绑定(bind)动态值的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23620070/