【 Avalonia UI 语言国际化 I18n】图文结合教学,保姆级教学,语言国际化就是这么简单(.Net C#)

发布于:2025-02-21 ⋅ 阅读:(21) ⋅ 点赞:(0)

完整项目地址

github : https://github.com/Crazy-GrowUp/AvaloniaI18nTest/tree/master
gitee :https://gitee.com/jack_of_disco/avalonia-i18n-test

0.项目新建 Properties 文件夹

Properties文件夹

对应的项目配置文件里面就会增加 <Folder Include="Properties\" />
Properties添加到项目中

1.项目添加新建项目

在 Properties 里面添加资源文件,命名为 Resource.resx
添加资源文件

文件位置

2.将自定义工具设置为 PublicResXFileCodeGenerator(重要)

右键 Resource.resx 文件,打开属性,修改属性中自定义工具为 PublicResXFileCodeGenerator
在这里插入图片描述

3.添加文本资源

添加文本资源
显示资源

4.安装扩展 ResXManager(推荐)

安装完成后,可能需要重启VS
ResXManager扩展

5.添加多国语言

方式一:右键 Resource.resx 使用 ResXManager 打开
添加其他语言
添加其他语言2

Properties 文件夹下面就多了一个 Resource.en.resx
x.en.resx文件

方式二:手动添加多国语言文件

比如我们要添加中文,那么就新建 Resource.zh.resx 资源文件
添加x.zh.resx文件

然后将对应的翻译填写到资源文件中
资源翻译

6.在 .axaml 文件中使用

  1. 在 MainWindow.axaml 中加上 xmlns:prop="using:AvaloniaI18nTest.Properties"
  2. 通过 {x:Static prop:Resource.Name} 进行使用
    axaml中使用

7.在代码中使用

  1. 在 MainWindowViewModel 中 使用 using AvaloniaI18nTest.Properties; 或者 using prop = AvaloniaI18nTest.Properties;

  2. 取出其中的值

     public string ResxName { get; } = Resource.Name;
     public string ResxName2 { get; } = prop.Resource.Name;   
    

代码中使用资源

  1. 在 axaml 中显示

    axaml中使用

8.切换语言

切换需要需要在 App.axaml.cs 中的 Initialize() 方法中进行设置
切换语言

 // 不写或者为空就是默认系统语言
 // Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(""); 
 // 修改语言
 // Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("zh"); 
 Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en");