WPF 实现语言切换
源码下载:LanguageStyle.zip
第一步:创建language文件夹,并创建文件(zh-cn.xaml、en-us.xaml)
zh-cn.xaml | en-us.xaml | ||
|
|
第二步:修改配置文件(App.config)
< appSettings > < add key="language" value="en-us"/> </ appSettings > |
第三步:App启动资源文件
public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base .OnStartup(e); // 获取配置 if (ConfigurationManager.AppSettings[ "language" ] != null ) { if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings[ "language" ])) { var requestedLanguage = String.Format( "pack://application:,,,/;component/language/{0}.xaml" , ConfigurationManager.AppSettings[ "language" ]); var resource = Application.Current.Resources.MergedDictionaries.FirstOrDefault(rd => rd.Source != null && rd.Source.OriginalString.ToLower().Contains( "language" )); if (resource == null ) { ResourceDictionary resourceDictionary = new ResourceDictionary(); resourceDictionary.Source = new Uri(requestedLanguage, UriKind.RelativeOrAbsolute); Application.Current.Resources.MergedDictionaries.Add(resourceDictionary); } } } } protected override void OnExit(ExitEventArgs e) { // 在这里处理应用程序退出逻辑 base .OnExit(e); } } |
第四步:选择并保存默认语言
public void SetLanguage( string language = "zh-cn" ) { if ( string .IsNullOrEmpty(language)) language = "zh-cn" ; // 获取当前语言 var resourceDictionary = Application.Current.Resources.MergedDictionaries.FirstOrDefault(rd => rd.Source != null && rd.Source.OriginalString.ToLower().Contains( "language" )); if (resourceDictionary != null ) { //移除语言 Application.Current.Resources.MergedDictionaries.Remove(resourceDictionary); //添加语言 string requestedLanguage = $ "pack://application:,,,/;component/language/{language}.xaml" ; resourceDictionary.Source = new Uri(requestedLanguage, UriKind.RelativeOrAbsolute); Application.Current.Resources.MergedDictionaries.Add(resourceDictionary); // 保存配置 var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings[ "language" ].Value = language; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name); MessageBox.Show( "保存成功" ); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2021-05-28 WPF System.Windows.Controls
2021-05-28 WPF TextBlock
2021-05-28 WPF ListView
2021-05-28 WPF ProgressBar
2021-05-28 WPF DatePicker
2021-05-28 WPF 布局
2021-05-28 WPF TextBox