Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Localization for Label StringFormat in Xamarin.Forms

In xamarin forms I can localize the text in a label like:
<Label Text="{x:Static resources:AppResources.Text}"/>

With a namespace for the resources:
<ContentView ... xmlns:resources="clr-namespace:ProjectName.Resources;assembly=ProjectName">

I can also bind some value and add a string format to the label:
<Label Text="{Binding Value, StringFormat='The value is: {0}' }"/>

The problem is that the text The value is: is not localized.

Who can I do both, bind a value and localize the StringFormat?

like image 558
Oscar Fraxedas Avatar asked Jun 12 '18 19:06

Oscar Fraxedas


1 Answers

I found the answer at Localizing XAML

I had to add the text The value is: {0} to the resource file.
I needed to add an IMarkupExtension for the translation. I added the class to the same namespace as the resource file.

[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;
    }
}

and use it like:

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

like image 129
Oscar Fraxedas Avatar answered Oct 26 '22 20:10

Oscar Fraxedas