Localization for Label StringFormat in Xamarin.Forms
Asked Answered
R

2

7

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?

Rutaceous answered 12/6, 2018 at 19:47 Comment(0)
R
9

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}}" />

Rutaceous answered 12/6, 2018 at 19:47 Comment(0)
S
2

I was able to just use the normal localized resources line without any extension, like so:

Text="{Binding WireValue, StringFormat={x:Static resources:AppResources.PaymentDetailsLine3}}"

Where PaymentDetailsLine3 is in my AppResources.resx as:

   <data
  name="PaymentDetailsLine3"
  xml:space="preserve">
  <value>PaymentDetailsLine3 {0}</value>
Sublimate answered 24/8, 2020 at 23:30 Comment(1)
Thanks for this. I could not it to work, because I had retained the single quotes around the StringFormat value from when it was a literal before. Your answer showed me that all I should have done was remove the quotes...Margaux

© 2022 - 2024 — McMap. All rights reserved.