Multilingual support is one of the most common requirements for mobile apps. One of the great parts of building mobile apps with Xamarin is that handling multiple languages is super simple. It may seem like a difficult task, but it is relatively easy if you leverage built in .NET capabilities to add multilingual support to your apps. A while back I wrote an article on how to do add multilingual support with my plugin. In this article, I will talk about some typical problems that you might face when adding multilingual support and how to solve them. Let’s start!

Setting App Culture

When multiple languages are handled in our application, a typical use case is to support that the user can change the language within the application. The problem can come up because we often bind our XAML strings to the AppResources class directly. This means we don’t have a mechanism to observe when the language changes and we would need to restart the application to get those strings updated.

The code to set the Culture is usually set in the App startup code:

Thread.CurrentThread.CurrentUICulture = language;
AppResources.Culture = language;
App.Current.MainPage = new NavigationPage(new MainPage());

Mastering multilingual in Xamarin.Forms

While this works, restarting our entire application could be painful and isn’t a good user experience.

Improving Runtime Changes

As I mentioned, the main problem with this is approach is that we bind to the AppResources class;s strings directly in the XAML. Or the app is using code behind and a translate class that returns a string with the text changed.

When I was looking for a solution I found this great idea on StackOverflow with a localization manager.

I created a LocalizationResourceManager class that handles language changes and also will have a property with the translation. When the language changes it will invalidate that string so it will force the property to change.

 public class LocalizationResourceManager : INotifyPropertyChanged
    {
        public static LocalizationResourceManager Instance { get; } = new LocalizationResourceManager();

        public string this[string text]
        {
            get
            {
                return AppResources.ResourceManager.GetString(text, AppResources.Culture);
            }
        }

        public void SetCulture(CultureInfo language)
        {
            Thread.CurrentThread.CurrentUICulture = language;
            AppResources.Culture = language;

            Invalidate();
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void Invalidate()
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(null));
        }
    }

#developers #xamarin

Mastering Multilingual in Xamarin.Forms | Xamarin Blog
8.70 GEEK