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

C# 直接在XAML中使用.resw文件中的字符串,c#,xaml,localization,uwp-xaml,C#,Xaml,Localization,Uwp Xaml,我知道从.resw文件引用本地化字符串的常用方法如下: <string name="Hello">Hello, World!</string> <Page.Resources> <local:LocalizeConverter x:Key="LocalizeConverter" /> </Page.Resources> XAML: 但是也可以这样做吗: <string name="Hello">Hello, Wo

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

<string name="Hello">Hello, World!</string>
<Page.Resources>
    <local:LocalizeConverter x:Key="LocalizeConverter" />
</Page.Resources>
XAML:

但是也可以这样做吗:

<string name="Hello">Hello, World!</string>
<Page.Resources>
    <local:LocalizeConverter x:Key="LocalizeConverter" />
</Page.Resources>
XAML(伪代码):


我之所以想在第二次考试中这样做,是因为这是一个我正在从iOS和Android移植到WP的应用程序。我想将iOS或Android字符串文件转换为.resw语法,但不需要检查每个字符串并添加.Content或.Text或它的任何用途。有没有一个简单的解决方案?

我曾经做过类似的事情,我们在Android字符串资源文件中添加了任何新字符串,然后使用自定义构建工具将其转换为iOS和Windows格式

Android字符串可能如下所示:

<string name="Hello">Hello, World!</string>
<Page.Resources>
    <local:LocalizeConverter x:Key="LocalizeConverter" />
</Page.Resources>
现在,让该转换器可用于您的XAML,可能是这样的:

<string name="Hello">Hello, World!</string>
<Page.Resources>
    <local:LocalizeConverter x:Key="LocalizeConverter" />
</Page.Resources>
请注意,我们不向转换器提供任何值。(在WPF中,我会创建一个标记扩展。遗憾的是,这个选项在UWP中不可用,所以我提出了这个无值转换器选项作为替代。)

<>如果你想变得更漂亮,考虑一下:

<Button
    Content="{x:Bind Language, Converter={StaticResource LocalizeConverter}, ConverterParameter=Hello, Mode=OneWay}"
/>


如果您将资源本地化为其他语言,则可以动态更改语言。(注意
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中:

我们不能用这种方法直接使用
resx
文件吗?我假设OP也这样做了。是的,我可以:)如果您正在阅读本文并且有兴趣重新使用现有的
resx
文件,请查看我的答案:
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;
    }
}