即时刷新 UI 语言

Jon*_*Jon 5 c# xamarin.forms

我正在按照本指南本地化我的应用程序。我不想获得系统语言,所以我不使用ILocalize接口和依赖服务。我有这 3 个英语、西班牙语和法语的 resx 文件:

  • 应用资源.es.resx
  • 应用资源.fr.resx
  • AppResources.resx(英文)

这是我TestPage.xaml使用TranslateExtension指南中的类的代码:

<?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>
Run Code Online (Sandbox Code Playgroud)

使用此代码,我初始化语言设置:

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

在这种情况下,文本以西班牙语显示。但我想在页面显示后更改语言(例如,使用LanguageSettingsPage用户可以在应用程序运行时更改语言)。

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
}
Run Code Online (Sandbox Code Playgroud)

如何刷新页面以显示法语文本而无需new TestPage()再次执行?

Tut*_*rge 0

将 Text 属性的所有 Setter 保留在 OnAppearing() 方法上,然后从设置页面返回后,它将从 resx 文件中获取最新值。即使您返回页面,也会调用 OnAppearing() 方法。但对于同一页面,要更改语言,必须再次呈现页面或重新加载该页面中元素的 Text 属性。