完整項目地址
github : https://github.com/Crazy-GrowUp/AvaloniaI18nTest/tree/master
gitee :https://gitee.com/jack_of_disco/avalonia-i18n-test
0.項目新建 Properties 文件夾
對應的項目配置文件里面就會增加 <Folder Include="Properties\" />
1.項目添加新建項目
在 Properties 里面添加資源文件,命名為 Resource.resx
2.將自定義工具設置為 PublicResXFileCodeGenerator(重要)
右鍵 Resource.resx
文件,打開屬性,修改屬性中自定義工具為 PublicResXFileCodeGenerator
3.添加文本資源
4.安裝擴展 ResXManager(推薦)
安裝完成后,可能需要重啟VS
5.添加多國語言
方式一:右鍵 Resource.resx
使用 ResXManager 打開
Properties 文件夾下面就多了一個 Resource.en.resx
方式二:手動添加多國語言文件
比如我們要添加中文,那么就新建 Resource.zh.resx
資源文件
然后將對應的翻譯填寫到資源文件中
6.在 .axaml 文件中使用
- 在 MainWindow.axaml 中加上
xmlns:prop="using:AvaloniaI18nTest.Properties"
- 通過
{x:Static prop:Resource.Name}
進行使用
7.在代碼中使用
-
在 MainWindowViewModel 中 使用
using AvaloniaI18nTest.Properties;
或者using prop = AvaloniaI18nTest.Properties;
-
取出其中的值
public string ResxName { get; } = Resource.Name;public string ResxName2 { get; } = prop.Resource.Name;
-
在 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");