WPF 本地化资源文件及运行时切换语言

本地化资源文件创建

前期准备
Visual Studio 搜索并安装扩展插件 ResXManager

  1. 在项目内 Properties 文件夹内添加新建项 资源文件 Resource.resx

  2. 手动重新编译项目,然后 Resource.resx 右键菜单 -> 在 ResX Manager 中打开

  3. 打开后界面如下

    3.1.
    添加新语言,由于语言比较多,点开下拉稍等一会后选择需要添加的新语言

    3.2.
    检测代码引用,指示该键在项目中被调用的次数
    3.3.
    索引序号,表内键序号
    3.4.
    添加新键
    3.5.(重要)
    导入导出Excel是这个扩展最重要的一个功能,是用于给运维、产品、翻译等非开发人员做语言翻译的一个Excel表格,根据这个表内已有的Key来翻译相应语言,翻译完成后可直接导入到项目使用(第一语言在Excel中是空列名)

    (扩展内查看如下)

运行时切换语言
1.新建类 ResourceService

Copy
public class ResourceService : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private static readonly ResourceService _current = new ResourceService(); public static ResourceService Current => _current; readonly Properties.Resource resource = new Properties.Resource(); public Properties.Resource Resources => resource; protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null) { var handler = this.PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } public void ChangedCulture(string name) { Properties.Resource.Culture = CultureInfo.GetCultureInfo(name); this.RaisePropertyChanged("Resources"); } }

2.XAML使用
<Button Content="{Binding Resources.Hello, Source={x:Static local:ResourceService.Current}}"/>

3.切换语言

Copy
private void Changed() { ResourceService.Current.ChangedCulture("en-US"); }
posted @   _蔚蓝  阅读(2218)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示

"很酷,不需要打赏"