Search code examples
data-bindingxamarin.formslocalizationlabelstring-formatting

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?


Solution

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