Lang.Avalonia: Avalonia's multi-language solution seamlessly supports three formats: Resx/XML/JSON

Lang.Avalonia: Avalonia's multi-language solution seamlessly supports three formats: Resx/XML/JSON

This is a multi-language management library specially designed for the Avalonia framework. It reconstructs the multi-language support logic through plug-in architecture. It is not only compatible with traditional Resx resource files, but also adds support for XML and JSON formats. It also provides type-safe resource references, dynamic language switching and other capabilities make multi-language development simpler and more efficient.

最后更新 8/9/2025 7:58 PM
沙漠尽头的狼
预计阅读 8 分钟
分类
Avalonia UI
标签
.NET C# Avalonia UI architecture design security

Introduction: Why do you need Lang.Avalonia?

In cross-platform UI development, multi-language support is one of the core requirements for improving user experience. As a powerful cross-platform UI framework, Avalonia has flexible extensibility, but native multi-language solutions have limitations in format support, development efficiency and modular integration.

Lang.Avalonia came into being-this is a multi-language management library specially designed for the Avalonia framework. It reconstructs the multi-language support logic through plug-in architecture. It is not only compatible with traditional Resx resource files, but also adds new XML and JSON format support, while providing type-safe resource references, dynamic language switching and other capabilities, making multi-language development simpler and more efficient.

Core Features: Why choose Lang.Avalonia?

  • ** Multi-format compatibility **: Supports three language file formats: Resx (traditional. NET resource format), XML, and JSON, meeting the format preferences of different projects.
  • ** Type-safe references **: C#constant classes are automatically generated through the T4 template to avoid hard-coding the string Key, and resource reference errors can be detected during compilation.
  • 前后台无缝集成:提供XAML标记扩展({c:I18n})和C# API双端支持,前台UI绑定与后台逻辑调用同样便捷。
  • ** Dynamic language switching **: Supports switching language cultures during runtime, and the interface text can be updated in real time without restarting the application.
  • ** Modular management **: Supports splitting language files (such as main module and development module) by project modules, adapting to multi-team collaboration for large projects.
  • ** Lightweight and easy to integrate **: Plug-in design, you only need to install the NuGet package in the corresponding format, and initialization can be completed in a few lines of code.

Quick Start: Installation and Basic Configuration

Step 1: Install NuGet package

Depending on the language file format used by the project, select the corresponding installation command:

Language file formats installation command applicable scenarios
Resx Install-Package Lang.Avalonia.Resx Projects accustomed to traditional. NET Resx resource files
XML Install-Package Lang.Avalonia.Xml Projects that prefer lightweight XML format and require manual editing
JSON Install-Package Lang.Avalonia.Json Modern front-end style projects, scenarios where language files need to be shared across terminals

Step 2: Create a language file

按规范创建语言文件,建议统一放在项目根目录的i18n文件夹中,文件命名需包含文化标识(如zh-CN代表简体中文,en-US代表美式英语)。

Resx format

Resx文件需以基础文件名(如Resources.resx)+ 文化标识(可选)命名,基础文件默认为 fallback 语言,具体参考示例项目:

i18n/Resources.resx          // 默认语言(如英语)
i18n/Resources.zh-CN.resx    // 简体中文
i18n/Resources.zh-Hant.resx  // 繁体中文
i18n/Resources.ja-JP.resx    // 日语

XML format

XML files are directly named with cultural symbols, and each file independently stores resources for the corresponding language:

i18n/en-US.xml    // 美式英语
i18n/zh-CN.xml    // 简体中文
i18n/zh-Hant.xml  // 繁体中文
i18n/ja-JP.xml    // 日语

Example of JSON format

JSON files are also named after cultural identifiers and use a key-value pair structure to store resources:

i18n/en-US.json    // 美式英语
i18n/zh-CN.json    // 简体中文
i18n/zh-Hant.json  // 繁体中文
i18n/ja-JP.json    // 日语

Step 3: Generate type-safe resource constants (T4 template)

为避免硬编码资源Key(如直接写字符串"SettingView.Title"),通过T4模板自动生成C#常量类,支持编译期校验。

Operation steps:

  1. 从Lang.Avalonia.XX.Demo示例项目中复制对应格式的T4模板(Resx/XML/JSON模板不同),放入项目的i18n文件夹(需自行创建)。
  2. 模板会自动扫描i18n文件夹的语言文件,生成语言资源的常量类
  3. When a Key is added/modified to the language file, open the T4 template and press Ctrl + S to generate it again.

Practical Use: Front and Back Integration Guide

Initialize the Multi-Language Manager

在应用启动时(推荐在App.axaml.csInitialize方法中)初始化多语言管理器,预加载语言资源:

// 引入命名空间
using Lang.Avalonia;
using Lang.Avalonia.Resx; // 对应格式的命名空间(Resx/Xml/Json)
using System.Globalization;

public override void Initialize()
{
    base.Initialize();
    // 初始化Resx格式(其他格式替换为XmlLangPlugin/JsonLangPlugin)
    I18nManager.Instance.Register(
        plugin: new ResxLangPlugin(),  // 格式插件
        defaultCulture: new CultureInfo("zh-CN"),  // 默认语言
        error: out var error  // 错误信息(可选)
    );
    if (!string.IsNullOrEmpty(error))
    {
        // 处理初始化错误(如文件不存在)
        Console.WriteLine($"多语言初始化失败:{error}");
    }
}

Front-end XAML binding use

通过{c:I18n}标记扩展在AXAML中绑定资源,支持直接引用T4生成的常量类,还可指定特定语言:

<!-- 引入命名空间 -->
xmlns:c="https://codewf.com"  <!-- Lang.Avalonia的标记扩展命名空间 -->
xmlns:mainLangs="clr-namespace:Localization.Main"  <!-- 主模块常量类 -->
xmlns:developModule="clr-namespace:Localization.DevelopModule"  <!-- 开发模块常量类 -->

<!-- 绑定当前默认语言的资源 -->
<SelectableTextBlock Text="{c:I18n {x:Static mainLangs:SettingView.Title}}" />

<!-- 强制指定语言(如简体中文) -->
<SelectableTextBlock 
    Text="{c:I18n {x:Static developModule:Title2SlugView.Title}, CultureName=zh-CN}" 
/>

Background C#logic usage

通过I18nManager.Instance.GetResource方法在后台代码中获取资源,支持获取当前语言或指定语言的文本:

// 引入生成的常量命名空间
using Localization.Main;

// 获取当前默认语言的资源
var titleCurrent = I18nManager.Instance.GetResource(MainView.Title);

// 获取指定语言的资源(简体中文)
var titleZhCN = I18nManager.Instance.GetResource(MainView.Title, "zh-CN");

// 获取指定语言的资源(美式英语)
var titleEnUS = I18nManager.Instance.GetResource(MainView.Title, "en-US");

Advanced skills: dynamically switching languages

运行时切换语言只需设置属性I18nManager.Instance.Culture,界面会自动更新:

// 切换为英语
I18nManager.Instance.Culture = new CultureInfo("en-US");

// 切换为日语
I18nManager.Instance.Culture = new CultureInfo("ja-JP");

Considerations and best practices

  1. 文化标识规范:统一使用zh-CN(简体中文)、en-US(美式英语)等标准文化名称,避免混用zh_CN等非标准格式。
  2. ** Modular splitting **: It is recommended to split language files (such as main module and user module) according to functional modules for large projects. The T4 template will automatically generate constant classes for the corresponding module to avoid Key conflicts.
  3. Fallback机制:当指定语言的资源不存在时,会自动 fallback 到默认语言(初始化时指定的defaultCulture),建议保留默认语言文件作为兜底。
  4. ** Performance optimization **: Language resources will be cached during initialization, which is suitable for scenarios where languages are frequently switched; if the language file is large, consider asynchronous loading (it needs to be combined with Avalonia's asynchronous initialization mechanism).

conclusion

Lang.Avalonia has greatly simplified the multi-language development process of the Avalonia project through plug-in design, multi-format support and type-safety features. Whether you are traditional Resx users or modern projects that prefer XML/JSON, you can quickly integrate and enjoy an efficient multilingual management experience.

If you encounter problems during use or need to extend a new format, you can refer to Lang.Avalonia's plug-in interface to implement a custom language plug-in. You are also welcome to participate in project contributions!

Warehouse address: github.com/dotnet9/Lang.Avalonia

Keep Exploring

延伸阅读

更多文章