Wednesday September 18th, 2019

Xamarin.Forms Multilingual

By Ebubekir Sezer

Hello, When we develop an application we want it to be a global application. For that we need to support different languages in the application and thanks to that we may have more user. I develop Xamarin.Forms application and to add different languages in Xamarin.Forms application we need to use a plugin. The name of the plugin is Plugin.Multilingual, I found this plugin with research on the web. I show you how to implement this plugin.

Firstly, I added the Plugin.Multilingual via nuget package manager. After that, I create a folder which name is Helper and I create TranslateExtension class. I wrote these codes in the TranslateExtension class.

namespace XamarinLanguage.Helper
{
    [ContentProperty("Text")]
    public class TranslateExtension : IMarkupExtension
    {
        const string ResourceId = "XamarinLanguage.AppResources";

        static readonly Lazy<ResourceManager> resmgr =
            new Lazy<ResourceManager>(() =>new ResourceManager(ResourceId, typeof(TranslateExtension).GetTypeInfo().Assembly));

        public string Text { get; set; }

        public object ProvideValue(IServiceProvider serviceProvider)
        {
            if (Text == null)
                return "";

            var ci = CrossMultilingual.Current.CurrentCultureInfo;
            var translation = resmgr.Value.GetString(Text, ci);

            if (translation == null)
            {
                translation = Text; 
            }
            return translation;
        }
    }
}

After the helper class, I added a text file but the extension is .resx. It is important to file extension be .resx. I added AppResources.resx, AppResources.es.resx, AppResources.tr.resx. So I support the three different lanuages these are English, Spanish and Turkish. In the AppResources, I translate the every word which i used in the app.

AppResources.resx

AppResources.es.resx

AppResources.tr.resx

Now, I define the helper folder in my page

xmlns:translator="clr-namespace:XamarinLanguage.Helper"

Then using the translator, I translate the words and here is the my design codes;

<StackLayout VerticalOptions="Center"
                 HorizontalOptions="Center">
        <Label Text="{translator:Translate Hello}" 
               FontSize="Large"
               FontAttributes="Bold"
               TextColor="Black"/>
        <Button Text="{translator:Translate Click}" 
                BackgroundColor="DarkBlue"
                TextColor="Yellow"/>
        
    </StackLayout>

Screen Outputs;

To make this project, I looked this project. For your questions you can reach me via e-mail or comments.