Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh UI language on the fly

I'm following this guide to localize my app. I don't want to get system language so I don't use ILocalize interface and dependecy services. I have these 3 resx files for English, Spanish and French languages:

  • AppResources.es.resx
  • AppResources.fr.resx
  • AppResources.resx (English)

This is my TestPage.xaml code using TranslateExtension class from guide:

<?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:t="clr-namespace:LanguageTest.Resources;assembly=LanguageTest.Resources"
             x:Class="LanguageTest.TestPage">
    <Label Text="{t:Translate TestText}" VerticalOptions="Center" HorizontalOptions="Center" />
</ContentPage>

With this code I initilize language settings:

public App ()
{
    // I can change among "en", "es" and "fr"
    AppResources.Culture = new CultureInfo("es"); 
    this.MainPage = new NavigationPage(new TestPage());
}

I this case the texts are displayed in Spanish. But I want to change the language after the pages are displayed (for example, using a LanguageSettingsPage the user can change the language while the app is running).

public App ()
{
    AppResources.Culture = new CultureInfo("es"); 
    this.MainPage = new NavigationPage(new TestPage());
    AppResources.Culture = new CultureInfo("fr");
    // At this point the texts are diplayed in Spanish, not in French
}

How can I refresh de page to display French texts without doing new TestPage() again?

like image 851
Jon Avatar asked Nov 09 '22 08:11

Jon


1 Answers

this is not an specific solution for Resx, but it will let you load any language on user demand. No need to set strings manually as bindings will do the job. Take a look at I18NPortable and the samples. It´s pretty easy to get it up and running.

Binding sample:

<Button Text="{Binding Strings[key]}" />

To change the language on the fly (will update all the bindings):

I18N.Current.Locale = "fr";
like image 132
xleon Avatar answered Nov 14 '22 21:11

xleon