WPF的一种动态切语言方法
程序员文章站
2022-10-29 14:14:11
使用 resx 文件,可以动态切换语言, 新建Lang.zh-CN.resx Lang.en-US.resx 资源文件 新建空类Lang.cs 新建如下类: public class LanguageManager : INotifyPropertyChanged { private readonl ......
使用 resx 文件,可以动态切换语言,
新建lang.zh-cn.resx lang.en-us.resx 资源文件
新建空类lang.cs
新建如下类:
public class languagemanager : inotifypropertychanged { private readonly resourcemanager _resourcemanager; private static readonly lazy<languagemanager> _lazy = new lazy<languagemanager>(() => new languagemanager()); public static languagemanager instance => _lazy.value; public event propertychangedeventhandler propertychanged; private languagemanager() { _resourcemanager = new resourcemanager(typeof(lang)); } public string this[string name] { get { if (name == null) { throw new argumentnullexception(nameof(name)); } return _resourcemanager.getstring(name); } } public void changelanguage(cultureinfo cultureinfo) { cultureinfo.currentculture = cultureinfo; cultureinfo.currentuiculture = cultureinfo; propertychanged?.invoke(this, new propertychangedeventargs("item[]")); } }
使用方法:
<textblock fontsize="20" margin="10" text="{binding [string1], source={x:static local:languagemanager.instance}}"/>
切换语言:
languagemanager.instance.changelanguage(new cultureinfo("zh-cn"));
源码已上传至gitgub
上一篇: 【WPF学习】第五十四章 关键帧动画