Xamarin.Forms中标签StringFormat的本地化

Osc*_*das 6 data-binding label localization string-formatting xamarin.forms

在xamarin形式中,我可以将文本本地化为一个标签,例如:
<Label Text="{x:Static resources:AppResources.Text}"/>

使用资源的命名空间:
<ContentView ... xmlns:resources="clr-namespace:ProjectName.Resources;assembly=ProjectName">

我还可以绑定一些值并将字符串格式添加到标签:
<Label Text="{Binding Value, StringFormat='The value is: {0}' }"/>

问题在于文本值是:未本地化。

谁可以同时绑定值和本地化StringFormat?

Osc*_*das 7

我在本地化XAML中找到了答案

我必须将文本添加到资源文件中:{0}
我需要为翻译添加IMarkupExtension。我将类添加到与资源文件相同的名称空间。

[ContentProperty("Text")]
public class TranslateExtension : IMarkupExtension
{
    private readonly CultureInfo _ci;

    static readonly Lazy<ResourceManager> ResMgr = new Lazy<ResourceManager>(
        () => new ResourceManager(typeof(AppResources).FullName, typeof(TranslateExtension).GetTypeInfo().Assembly));

    public string Text { get; set; }

    public TranslateExtension()
    {
        if (Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.Android)
        {
            _ci = DependencyService.Get<ILocalize>().GetCurrentCultureInfo();
        }
    }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        if (Text == null)
            return string.Empty;

        return ResMgr.Value.GetString(Text, _ci) ?? Text;
    }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

<Label Text="{Binding Value, StringFormat={resources:Translate LabelTextTheValueIs}}" />