WPF 实现语言动态切换(无刷新)

概述:

  如何动态加载资源字典进行切换。

一:新建资源字典

  新建资源字典 en-us.xaml,zh-cn.xaml,并添加 【xmlns:s="clr-namespace:System;assembly=mscorlib"】。

  (如何访问 System 名称空间中的基本类型,并将其映射为前缀 s:)

zh-cn.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:s="clr-namespace:System;assembly=mscorlib">
    <s:String x:Key="lgLanguage">语言</sys:String>
</ResourceDictionary>

 en-us.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:s="clr-namespace:System;assembly=mscorlib">
    <s:String x:Key="lgLanguage">Language</sys:String>
</ResourceDictionary>

二:将资源字典添加至 App.xaml 中

两个字典中存在相同 key 值(如 lgLanguage),没有动态修改的话将会默认后添加的资源字典生效。

复制代码
<Application x:Class="xxx.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors"
             xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
             StartupUri="MainWindow.xaml" Exit="App_Exit">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>                
                <ResourceDictionary Source="Resources/Language/zh-cn.xaml" />
                <ResourceDictionary Source="Resources/Language/en-us.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>
复制代码

三:在 App.config 中添加你想要使用的键值对

<app key="Language" value="en-us" />

四:在 App.xaml.cs 中添加所需操作

复制代码
private static string Language {get; set;}

//获取默认语言
private void GetLanguage()
{
    Language = sting.Empty;
    try
    {
        Language = ConfigurationManager.AppSettings["Language"];
    }
    catch(Exception ex){}
    Language = string.IsNullOrEmpty(Language) ? "en-us" : Language;
    UpdateLanguage();
}

//更换语言
public static void UpdateLanguage()
{
  List<ResourceDictionary> dictionaryList = new List<ResourceDictionary>();
  foreach (ResourceDictionary dictionary in Application.Current.Resources.MergedDictionaries)
  {
    dictionaryList.Add(dictionary);
  }
  string requestedLanguage = string.Format(@"Resources/Language/{0}.xaml", Language);
  ResourceDictionary resourceDictionary = dictionaryList.FirstOrDefault(d => d.Source.OriginalString.Equals(requestedLanguage));
  if (resourceDictionary == null)
  {
    //第一次加载时默认使用英语
    requestedLanguage = @"Resources/Language/en-US.xaml";
    resourceDictionary = dictionaryList.FirstOrDefault(d => d.Source.OriginalString.Equals(requestedLanguage));
  }
  if (resourceDictionary != null)
  {
    Application.Current.Resources.MergedDictionaries.Remove(resourceDictionary);
    Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);
  }
}

//保存语言(下次打开与本次选择保持一致)
private void SaveLanguage()
{
    try
    {
        bool isModified = falase;
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        if(ConfigurationManager.AppSettings["Language"] != null)
        {    
            isModified = true;
        }
        if(isModified)
        {    
            config.AppSettings.Settings.Remove("Language");
        }
        config.AppSettings.Settings.Add("Language",Language);
        config.Save(ConfigurationSavaMode.Modified);
        //刷新
        ConfigurationManager.RefreshSection("appSettings");
    }
    catch(Exception ex){}
 }

//退出保存
private void App_Exit(object sender, ExitEventArgs e)
{
    SaveLanguage();
    //关闭所有进程
    System.Environment.Exit(0);
}
复制代码

五:添加选择语言命令

自行添加两个按钮,直接绑定 Click 事件即可。

复制代码
private void btnEn_Click(object sender, RoutedEventArgs e)
{
    App.Language = "en-us";
    App.UpdateLanguage();
}
private void btnZh_Click(object sender, RoutedEventArgs e)
{
    App.Language = "zh-cn";
    App.UpdateLanguage();
}
复制代码

六:在界面需要的位置添加动态资源

<Button Content="{DynamicResource lgChange}" />

关于 appSettings 配置节的保存问题可以查看:WPF C# 读取修改保存 App.config 文件

posted @   LCL059  阅读(537)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示