Avalonia 实现多语言

1.在项目中创建 I18n 目录,存放多语言相关的文件

2.添加 ResX 文件

默认 Resource.resx 为英语,其他语言添加 XXX 来区分,

如:中文- Resource.zh-CN.resx、日文 – Resource.ja-JP.resx

(不知道语言编码的,可以查阅 每个国家对应的语言Locale和国家代码对照表

3.安装 ResXManager 来统一管理多语言

4.将主文件 Resource.resx 改为 tt (Text Template)模式

在 Resource.resx 右键选择使用 ResX Manager 打开

为了后续可以正常使用字段验证([Required(StringResourceKey.XXX)]),所以需要将 Resource.resx 改为 tt 模式,

如果修改不了,则需要重启 Visual Studio,再进行修改,修改后,I18n\Resource 右上角会出现蓝色 TT 字样

修改后的文件目录:

(系统自动生成 Resoruces.Designer.t4 和 Resource.Designer.tt 文件)

4.添加 Language.tt 文件

方便在代码中访问 Resource 中的字段

复制以下代码到 Language.tt 文件中

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Xml.Linq" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Xml.Linq" #>
<#@ import namespace="System.IO" #>
<#@ output extension=".cs" #>
//------------------------------------------------------------------------------  
// <auto-generated>  
//     This code was generated by a tool.  
//     Changes to this file may cause incorrect behavior and will be lost if  
//     the code is regenerated.  
// </auto-generated>  
//------------------------------------------------------------------------------
<#
    const string ResourceFileName = "Resource.resx";
#>

namespace <#=System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint").ToString()#>;

public static class Language
{
<#
    var resourceKeys = XElement.Load(this.Host.ResolvePath(ResourceFileName))
        .Elements("data")
        .Select(item => item.Attribute("name")?.Value)
        .Where(item => item != null);

    var resourceDesignerName = Path.GetFileNameWithoutExtension(ResourceFileName);

    foreach (string resourceKey in resourceKeys)
    {
#>
    public static readonly string <#= resourceKey #> = "<#= resourceKey #>";
<#
    }
#>
}

在 ResX 文件中添加新的字段时,需要打开 Language.tt 文件,然后手动保存一下,新增的字段就会自动添加到 Language.cs 文件中,如下:

5.安装 I18n 库

通过 Nuget 安装 AvaloniaExtensions.Axaml 类库

6.使用

6.1.在 axaml 界面使用

添加命名空间:

xmlns:i18n="<https://codewf.com>"
xmlns:language="using:你的项目命名空间.I18n"

使用(引用 key 为 Test 的字符串):

 <TextBlock Text="{i18n:I18n {x:Static language:Language.Test}}"/>

6.2.在 C# 后台代码使用

TestString = I18nManager.GetString(Language.TestString);

7.切换语言

I18nManager.Instance.Culture = new CultureInfo(language);//en、zh-CN

参考:

Avalonia 国际化之路:Resx 资源文件的深度应用与探索

WPF或Avalonia使用tt模板和resx文件实现国际化

https://github.com/Antelcat/I18N?tab=readme-ov-file
https://www.nuget.org/packages/AvaloniaExtensions.Axaml/1.0.3

Avalonia实现国际化-AvaloniaExtensions

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *