繁体   English   中英

如何本地化 Xamarin Forms 中的文本?

[英]How do I localize Text in Xamarin Forms?

我正在尝试在 Android 的 Xamarin Forms 项目中本地化文本。

我按照 教程设置了一个新项目作为测试环境,但是当我按下按钮时,文本的语言并没有改变。 Lang.resx(标准为德语)文件设置为公开,Lang.en.resx 文件设置为不生成代码。 这两个文件具有相同的键(switch-de、switch-en、welcome)。

更改语言后,我尝试关闭并重新打开应用程序,并且禁用了快速部署,但都没有解决问题。 文本保持德语。

这是 SwitchPage.xaml.cs:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace I18nTest
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class SwitchPage : ContentPage
    {
        public SwitchPage()
        {
            InitializeComponent();
            Content = new StackLayout
            {
                Margin = new Thickness(100),

                Children =
                {
                    welcomeLabel,
                    switchENButton,
                    switchDEButton
                }
            };
        }

        Label welcomeLabel = new Label
        {
            Text = Language.Lang.welcome,
            Margin = new Thickness(100, 100, 100, 50),
            FontSize = 80,
            HorizontalTextAlignment = TextAlignment.Center,
        };
        Button switchENButton = new Button
        {
            Text = Language.Lang.switch_en,
        };
        Button switchDEButton = new Button
        {
            Text = Language.Lang.switch_de,
        };


        private void Button_de_Clicked(object sender, EventArgs e)
        {
            CultureInfo.CurrentUICulture = new CultureInfo("de", false);
        }

        private async void Button_en_Clicked(object sender, EventArgs e)
        {
            CultureInfo.CurrentUICulture = new CultureInfo("en", false);
        }
    }
}

这是 SwitchPage.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"
             x:Class="I18nTest.SwitchPage"
             xmlns:resources="clr-namespace:i18nMalWieder.Language">

    <StackLayout>
    <Label Text="{x:Static resources:Lang.welcome}" FontSize="Header" Margin="100,100,100,50" HorizontalTextAlignment="Center"/>
    <Button Text="{x:Static resources:Lang.switch_de}" Clicked="Button_de_Clicked" HeightRequest="100"/>
    <Button Text="{x:Static resources:Lang.switch_en}" Clicked="Button_en_Clicked" HeightRequest="100"/>
    </StackLayout>
</ContentPage>

Xamarin 的本地化文档说,使用 CurrentUICulture 可能并不理想:

测试本地化最好通过更改您的设备语言来完成。 可以在代码中设置 System.Globalization.CultureInfo.CurrentUICulture 的值,但跨平台的行为不一致,因此不建议进行测试。

您的实现可能运行良好; 但是,务实地更改语言可能与从手机设置更改设备语言的方式不同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM