c# - 使用 .NET 的 Xamarin iOS 本地化

标签 c# android ios localization xamarin

我正在尝试在 Xamarin iOS/Android 项目的可移植类库中使用 .NET 本地化。我已按照以下步骤操作:

How to use localization in C#

代码如下:

string sText = strings.enter_movie_name;
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("fr");
sText = strings.enter_movie_name;
lblEnterMovieName.Text = sText;

我也试过:

ResourceManager resman = new ResourceManager(typeof(MyApplication.strings));
string sText = resman.GetString("enter_movie_name", new CultureInfo("fr"));

我创建了 strings.resx,其中 enter_movie_name 等于“Enter movie name:”,strings.fr.resx 等于“Entre la movie name:”

但是,sText 总是以“输入电影名称:”结束。我似乎无法获得“Entre la movie name:”版本。

我还在 Cross-platform Localization 看到了帖子但无法解决。我也不想在 Localization on Xamarin.iOS 使用 iOS 特定版本因为我希望能够从独立于平台的库中获取我的字符串。

谁能指出我哪里出错了?

最佳答案

我创建了一个有点丑陋的解决方案,但它确实有效。我所做的是在我的可移植类库 (PCL) 中创建了一个名为“strings”的文件夹,并在该文件夹中创建了名为:

  • 字符串.resx
  • strings_fr.resx
  • strings_ja_JP.resx

我已将所有这些全部设置为嵌入式资源,并使用自定义工具作为 ResXFileCodeGenerator。这意味着我对每种语言都有一个单独的资源 DLL。

在 iOS 中,我可以通过调用获取区域设置:

string sLocale = NSLocale.CurrentLocale.LocaleIdentifier;

我猜有一个 Android 等价物使用 Locale但我不知道它是什么。

这给了我一个像“ja_JP”或“fr_FR”或“en_GB”这样的字符串(注意它们是下划线,而不是破折号)。然后,我将其与我创建的以下静态类一起使用,以检索适当的资源管理器并从中获取字符串。

如果给定一个语言环境 aa_BB,它首先查找 strings_aa_BB,然后查找 strings_aa,最后查找字符串。

public static class Localise
{
    private const string STRINGS_ROOT = "MyPCL.strings.strings";

    public static string GetString(string sID, string sLocale)
    {
        string sResource = STRINGS_ROOT + "_" + sLocale;
        Type type = Type.GetType(sResource);
        if (type == null)
        {
            if (sLocale.Length > 2) {
                sResource = STRINGS_ROOT + "_" + sLocale.Substring(0, 2); // Use first two letters of region code
                type = Type.GetType(sResource);
            }
        }
        if (type == null) {
            sResource = STRINGS_ROOT;
            type = Type.GetType(sResource);
            if (type == null)
            {
                System.Diagnostics.Debug.WriteLine("No strings resource file when looking for " + sID + " in " + sLocale);
                return null; // This shouldn't ever happen in theory
            }
        }
        ResourceManager resman = new ResourceManager(type);
        return resman.GetString(sID);
    }
}

一个如何使用它的例子(引用上面的代码)是:

string sText = Localise.GetString("enter_movie_name", sLocale);
lblEnterMovieName.Text = sText;

这样做的一个显着缺点是所有 View 都需要以编程方式设置其文本,但优点是可以完成一次翻译,然后在多个平台上重复使用。它们还与自己的 DLL 中的主要代码保持分离,因此可以在必要时单独重新编译。

关于c# - 使用 .NET 的 Xamarin iOS 本地化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20569392/

相关文章:

c# - 强制执行 JIT

c# - 联播 .NET 流

java - 需要有关我的 fragment 的帮助

java - SDKmanager : Warning: Could not create setting. java.lang.IllegalArgumentException

ios - UIStackView 比例布局,仅具有内在内容大小

c# - 带按钮控件的 DataGridView - 删除行

c# - 试图将模型传递给 View 但出现异常

android - android如何计算res目录

ios - 无法检查应用程序包

ios - 为什么我的子类变量不存在?