直接在XAML中使用.resw文件中的字符串
我知道从.resw文件引用本地化字符串的常用方法是这样的:
XAML:
Resources.resw:
ButtonUid.Content = "Hello World"
但也有可能像这样做:
XAML(伪代码):
Resources.resw:
buttonLabel = "Hello World"
我想在第二个例子中做到这一点的原因是因为这是一个我从iOS和Android移植到WP的应用程序。 我想将iOS或Android字符串文件转换为.resw语法,但不会遍历每个字符串并添加.Content或.Text或其他用途。 有一个简单的解决方案吗?
我曾经做过类似的事情,我们在Android字符串资源文件中添加了任何新字符串,然后使用自定义构建工具将这些字符串转换为iOS和Windows格式。
Android字符串可能如下所示:
Hello, World!
我们的工具将其转换为Windows字符串资源:
Hello, World!
接下来,添加一个对提供的值不起作用的转换器,而是假设其参数是资源ID:
public sealed class LocalizeConverter : IValueConverter { private static readonly ResourceLoader Loader = ResourceLoader.GetForViewIndependentUse("/Resources"); public object Convert(object value, Type targetType, object parameter, string language) { string resourceId = parameter as string; return !string.IsNullOrEmpty(resourceId) ? Loader.GetString(resourceId) : DependencyProperty.UnsetValue; } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotSupportedException(); } }
现在让您的XAML可以使用该转换器,可能是这样的:
最后,按如下方式设置Button
的Content
属性:
请注意,我们不向转换器提供任何值。 (在WPF中我会创建一个标记扩展。遗憾的是,这个选项在UWP中不可用,所以我想出了这个无值转换器选项作为替代方案。)
如果你想变得更加笨拙,请考虑一下:
如果您将资源本地化为其他语言,则可以动态更改语言。 (注意Mode=OneWay
而不是Mode=OneTime
。)
您可以使用CustomXamlResourceLoader
:
public class XamlResourceLoader : CustomXamlResourceLoader { private readonly ResourceLoader _loader; public XamlResourceLoader() { _loader = ResourceLoader.GetForViewIndependentUse(); } protected override object GetResource(string resourceId, string objectType, string propertyName, string propertyType) { return _loader.GetString(resourceId) ?? resourceId; } }
然后在App.xaml.cs构造函数中:
CustomXamlResourceLoader.Current = new XamlResourceLoader();
最后在你的xaml中: