c# - 跨平台本地化

标签 c# localization cross-platform xamarin.android xamarin

使用 Xamarin Android,可以为多语言应用程序创建本地化字符串,如他们的 Android 文档所示:

http://docs.xamarin.com/guides/android/application_fundamentals/resources_in_android/part_5_-_application_localization_and_string_resources

但是,我的模型中有各种 try/catch block ,它们将错误消息作为字符串发回。理想情况下,我希望让我的解决方案的模型和 Controller 部分完全跨平台,但我看不出有什么方法可以有效地本地化消息,而不会将非常特定于平台的 Android 上下文传递给模型。

有没有人知道如何实现这一点?

最佳答案

我正在使用 .net resource files而不是安卓的。它们使我能够访问代码中的字符串,无论它在哪里。

我唯一不能自动执行的是从布局中引用这些字符串。为了解决这个问题,我编写了一个快速实用程序来解析 resx 文件并创建一个具有相同值的 Android 资源文件。它在 Android 项目构建之前运行,因此所有字符串在构建时就位。

免责声明:我还没有用多种语言实际测试过它。

这是实用程序的代码:

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

namespace StringThing
{
    class Program
    {
        static void Main(string[] args)
        {
            string sourceFile = args[0];
            string targetFile = args[1];

            Dictionary<string, string> strings = LoadDotNetStrings(sourceFile);
            WriteToTarget(targetFile, strings);
        }

        static Dictionary<string, string> LoadDotNetStrings(string file)
        {
            var result = new Dictionary<string, string>();

            XmlDocument doc = new XmlDocument();
            doc.Load(file);

            XmlNodeList nodes = doc.SelectNodes("//data");

            foreach (XmlNode node in nodes)
            {
                string name = node.Attributes["name"].Value;
                string value = node.ChildNodes[1].InnerText;
                result.Add(name, value);
            }

            return result;
        }

        static void WriteToTarget(string targetFile, Dictionary<string, string> strings)
        {
            StringBuilder bob = new StringBuilder();

            bob.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            bob.AppendLine("<resources>");

            foreach (string key in strings.Keys)
            {
                bob.Append("    ");
                bob.AppendLine(string.Format("<string name=\"{0}\">{1}</string>", key, strings[key]));
            }

            bob.AppendLine("</resources>");

            System.IO.File.WriteAllText(targetFile, bob.ToString());
        }
    }
}

关于c# - 跨平台本地化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16958508/

相关文章:

c# - 从 Windows 8 Metro 风格应用建立与 Dynamics CRM Online Web 服务的连接

cross-platform - 超标量和 VLIW

java - 跨平台卓悦

caching - SCons 缓存如何与不同的操作系统和 CPU 架构配合使用?

c# - 在浏览器关闭时调用方法

c# - 有没有办法将此枚举转换为正确的类型

c# - 名称/值 .NET 集合或 .NET 名称/值字典?

ios - SW Reveal View Controller 权限/本地化

javascript - 带有 Angular 平移的 ng-repeat

iphone - 如何加载正确的本地化文件?