直接在 XAML 中使用 .resw 文件中的字符串

use*_*883 2 c# xaml localization uwp-xaml

我知道从 .resw 文件引用本地化字符串的常用方法如下:

XAML:

<Button x:Uid="ButtonUid" />
Run Code Online (Sandbox Code Playgroud)

资源.resw:

ButtonUid.Content = "Hello World"
Run Code Online (Sandbox Code Playgroud)

但也可以这样做:

XAML(伪代码):

<Button Content = "$buttonLabel" />
Run Code Online (Sandbox Code Playgroud)

资源.resw:

buttonLabel = "Hello World"
Run Code Online (Sandbox Code Playgroud)

我之所以要像第二个例子那样做,是因为这是一个我要从 iOS 和 Android 移植到 WP 的应用程序。我想将 iOS 或 Android 字符串文件转换为 .resw 语法,但无需遍历每个字符串并添加 .Content 或 .Text 或其用途。有一个简单的解决方案吗?

Fel*_*ino 6

您可以使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的 App.xaml.cs 构造函数中:
CustomXamlResourceLoader.Current = new XamlResourceLoader();

最后在你的 xaml 中:
<Button Content = "{CustomResource buttonLabel}" />