【问题标题】:How Change the CultureInfo Dynamically in xamarin forms如何以 xamarin 形式动态更改 CultureInfo
【发布时间】:2020-10-22 14:44:37
【问题描述】:

我需要创建一个支持多语言的应用程序。

所以我做了一个如下示例应用程序。

Page.xamal

<StackLayout
            VerticalOptions="CenterAndExpand">
            <Label Text="{x:Static local:AppResources.Title}" TextColor="Black"
                HorizontalOptions="CenterAndExpand" />

            <Button Text="{x:Static local:AppResources.ClickMe}" Clicked="Button1_Clicked"/>

            <Label Text="{x:Static local:AppResources.Title}" TextColor="Black"
                HorizontalOptions="CenterAndExpand" />

            <Button Text="{x:Static local:AppResources.ClickMe}" Clicked="Button2_Clicked"/>
            
        </StackLayout>

page.xamal.cs

private void Button1_Clicked(object sender, EventArgs e)
        {
            CultureInfo culture = new CultureInfo("th");
            AppResources.Culture = culture;
        }

作为 xmarin 表单文档,我设置了 AssemblyInfo.cs(公共文件夹)

[assembly: NeutralResourcesLanguage("en-GB")]

所以我的默认语言是“en-GB”。

我有 3 个 AppRerources.resx

  1. AppResources.resx
  2. AppResources.th.resx
  3. AppResources.en-GB.resx

但是当我按下第一个按钮时,我看不到该应用正在更改语言。

我错过了什么?

【问题讨论】:

标签: c# xamarin xamarin.forms


【解决方案1】:

关于更改当前文化信息,我建议你可以尝试使用Plugin.Multilingual来获取。

首先,通过nuget包安装Plugin.Multilingual,定义.resx文件如下:

默认情况下,在常量 ResourceId 中的 TranslateExtension.cs 文件中,它将假定您的资源文件已添加到项目的根目录中,并且 resx 文件被命名为 AppResources。如果您将其添加到文件夹或以不同的方式命名 resx 文件,您可以在此处进行更改。

public class TranslateExtension : IMarkupExtension
{
    const string ResourceId = "MultilingualSample.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)
        {

     #if DEBUG
            throw new ArgumentException(
                String.Format("Key '{0}' was not found in resources '{1}' for culture '{2}'.", Text, ResourceId, ci.Name),
                "Text");
  #else
            translation = Text; // returns the key, which GETS DISPLAYED TO THE USER
  #endif
        }
        return translation;
    }
}

更多详细信息,请看:

https://github.com/CrossGeeks/MultilingualPlugin

【讨论】:

  • 我目前正在使用这个,它在调试模式下工作,但不在发布模式下。你能给我你的样品吗
【解决方案2】:

在 CultureInfo 中传递您要设置的文化参数,例如在我的示例中,我将其设置为 German

CultureInfo ci = new CultureInfo("de-DE");
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    相关资源
    最近更新 更多