Use strings in .resw File directly in XAML

穿精又带淫゛_ 提交于 2019-12-02 00:25:08

You can use a 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;
    }
}

Then in your App.xaml.cs constructor:
CustomXamlResourceLoader.Current = new XamlResourceLoader();

And finally in your xaml:
<Button Content = "{CustomResource buttonLabel}" />

I once did something similar, where we added any new strings to the Android string resource file, then used custom build tools convert those into iOS and Windows formats.

An Android string might look like this:

<string name="Hello">Hello, World!</string>

Our tool converts this into a Windows string resource:

<data name="Hello">
  <value>Hello, World!</value>
</data>

Next, add a converter that does nothing to the provided value, but instead assumes its parameter is a resource 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();
    }
}

Now make that converter available to your XAML, perhaps something like this:

<Page.Resources>
    <local:LocalizeConverter x:Key="LocalizeConverter" />
</Page.Resources>

And finally, set your Button's Content property as follows:

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

Note that we don't supply any value to the converter. (In WPF I would have created a markup extension. Sadly, this option is not available in UWP, so I came up with this value-less converter option as an alternative.)

If you want to get even niftier, consider this:

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

This lets you change the language on the fly, if you have resources localized into other languages. (Note Mode=OneWay instead of Mode=OneTime.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!