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

  • WPF 本地化资源文件及运行时切换语言已关闭评论
  • 173 次浏览
  • A+
所属分类:.NET技术
摘要

本地化资源文件创建前期准备
Visual Studio 搜索并安装扩展插件 ResXManager在项目内 Properties 文件夹内添加新建项 资源文件 Resource.resx

本地化资源文件创建

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

  1. 在项目内 Properties 文件夹内添加新建项 资源文件 Resource.resx
    WPF 本地化资源文件及运行时切换语言

  2. 手动重新编译项目,然后 Resource.resx 右键菜单 -> 在 ResX Manager 中打开
    WPF 本地化资源文件及运行时切换语言

  3. 打开后界面如下
    WPF 本地化资源文件及运行时切换语言
    3.1.
    添加新语言,由于语言比较多,点开下拉稍等一会后选择需要添加的新语言
    WPF 本地化资源文件及运行时切换语言
    3.2.
    检测代码引用,指示该键在项目中被调用的次数
    3.3.
    索引序号,表内键序号
    3.4.
    添加新键
    3.5.(重要)
    导入导出Excel是这个扩展最重要的一个功能,是用于给运维、产品、翻译等非开发人员做语言翻译的一个Excel表格,根据这个表内已有的Key来翻译相应语言,翻译完成后可直接导入到项目使用(第一语言在Excel中是空列名)
    WPF 本地化资源文件及运行时切换语言
    (扩展内查看如下)
    WPF 本地化资源文件及运行时切换语言

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

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.切换语言

private void Changed() {     ResourceService.Current.ChangedCulture("en-US"); }