Projects

Lang.Avalonia

Avalonia UI plug-in multi-language library

项目说明

Lang.Avalonia

Lang.Avalonia

Lang.Avalonia 是面向 Avalonia UI 的插件化多语言库。核心包提供 XAML 标记扩展、绑定刷新流程、转换器、I18nManagerILangPlugin 契约;资源加载由 JSON、XML、RESX 插件实现,也可以使用 Source Generator 生成强类型资源 Key。

envelope

package description
Lang.Avalonia Core capabilities, including token extension, binding refresh, and resource management.
Lang.Avalonia.Json JSON resource provider.
Lang.Avalonia.Xml XML resource provider.
Lang.Avalonia.Resx RESX resource provider.
Lang.Avalonia.Analysis AdditionalFiles 编译期生成强类型 Key。

function

  • Unified AXAML and C#multilingual portal.
  • 通过 I18nManager.Instance.Culture 运行时切换语言。
  • JSON、XML、RESX 资源提供器统一实现 ILangPlugin
  • Supports default cultural fallback and original Key fallback.
  • 支持 T4 模板或 Lang.Avalonia.Analysis 生成强类型资源 Key。
  • Supports fixed cultural previews, formatted strings, and dynamic binding parameters.

quick start

Install the core package and a resource provider:

dotnet add package Lang.Avalonia
dotnet add package Lang.Avalonia.Json

I18n 目录创建语言文件,并将 JSON/XML 文件复制到输出目录:

<ItemGroup>
  <None Update="I18n\*.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

Register the plug-in when the application is launched:

using Lang.Avalonia;
using Lang.Avalonia.Json;
using System.Globalization;

I18nManager.Instance.Register(new JsonLangPlugin(), new CultureInfo("en-US"), out var error);
if (!string.IsNullOrWhiteSpace(error))
{
    // 记录或展示初始化错误。
}

Used generated constants in AXAML:

xmlns:c="https://codewf.com"
xmlns:mainLangs="clr-namespace:Localization.Main"

<SelectableTextBlock Text="{c:I18n {x:Static mainLangs:MainView.Title}}" />
<SelectableTextBlock Text="{c:I18n {x:Static mainLangs:MainView.Title}, CultureName=ja-JP}" />

The same Key is used in C#:

var title = I18nManager.Instance.GetResource(Localization.Main.MainView.Title);
var englishTitle = I18nManager.Instance.GetResource(Localization.Main.MainView.Title, "en-US");

Switch languages at runtime:

I18nManager.Instance.Culture = new CultureInfo("zh-CN");

Suitable for attention

  • The Avalonia project requires simultaneous support for JSON, XML or RESX multilingual resources.
  • I hope to read translated strings in AXAML and C#through a unified API.
  • I hope to use T4 or Source Generator to generate strongly typed keys and reduce hard-coded strings.
  • I hope that the interface binding can be automatically refreshed when switching languages.

warehouse