2

I try to create something like that:

<Label Text="{Binding oResult.hi, StringFormat='Hallo: {0}'}" />

And it works fine! But i wish that the String "Hallo" should get out from the resx file.

Like this:

<Entry Placeholder="{i18n:TranslateExtension Text=password}" IsPassword="true" />

Also i will do a combination of both.

Thank you!

Flo
  • 1,179
  • 3
  • 15
  • 43

1 Answers1

5

You could achieve this with a simple markup extension and strings in resx files.

Xaml extension:

using System;
using Xamarin.Forms.Xaml;
using Xamarin.Forms;
using System.Resources;

namespace i18n
{
    [ContentProperty("Key")]
    public class TranslateExtension : IMarkupExtension
    {
        public string Key { get; set; }
        static ResourceManager ResourceManagerInstance;

        #region IMarkupExtension implementation

        public static void Init(ResourceManager r){
            ResourceManagerInstance = r;   
        }

        public object ProvideValue(IServiceProvider serviceProvider)
        {
            if (ResourceManagerInstance == null)
            {
                throw new InvalidOperationException("Call TranslateExtension.Init(ResourceManager) in your App.cs");
            }
            return ResourceManagerInstance.GetString(this.Key);
        }

        #endregion
    }
}

Example App.cs:

using Xamarin.Forms;
using i18n;

namespace ResourceLocalizationMarkup
{
    public class App : Application
    {
        public App()
        {
            TranslateExtension.Init(Localization.Strings.ResourceManager);
            MainPage = new NavigationPage(new MyPage());
        }
    }
}

Example Xaml:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage 
    xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    xmlns:i18n="clr-namespace:i18n"
    x:Class="ResourceLocalizationMarkup.MyPage">

    <ContentPage.Content>
        <StackLayout Orientation="Vertical">
            <Label Text="{i18n:TranslateExtension hello_world}"/>
            <Label Text="{Binding Name, StringFormat={i18n:TranslateExtension thanks_user}}"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>
testing
  • 19,681
  • 50
  • 236
  • 417
Andrew Tavera
  • 388
  • 4
  • 9