WPF 多语言切换实战:实现界面语言动态更新

409 阅读2分钟

功能点说明

功能的关键在于:创建两个语言字典(中英文各一个),key和value键值对的那种

切换语言的时候,切换字典就行。

前端绑定key就行,自动显示value。

这里有一个很重要的问题,字段切换了,前端怎么会更新?用DynamicResource绑定就行,它会自动更新资源。

构建的关键代码如下:

Application.Current.Resources.MergedDictionaries.Remove(resourceDictionary);  

Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);

实战

首先,创建一个wpf项目:WPFMultipleLanguage.csproj

添加资源(语言字典)

增加两个资源文件:zh-cn.xaml和en-us.xaml

选中项目-右键点击-添加-资源字典

zh-cn.xaml资源字典的代码如下

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:WPFMultipleLanguage"
                    xmlns:s="clr-namespace:System;assembly=mscorlib">
    <s:String x:Key="OK">确认</s:String>
    <s:String x:Key="Cancle">取消</s: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="OK">Sure</s:String>
    <s:String x:Key="Cancle">NoSure</s:String>
</ResourceDictionary>

这样,资源字典就完成了

资源字典添加还不算完成,必须将字典添加到系统

打开App.xaml

中间加上字典声明

<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="en-us.xaml" /> <!--"Resources/Language/en-us.xaml"-->
        <ResourceDictionary Source="zh-cn.xaml" /> <!--"Resources/Language/zh-cn.xaml"-->
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

注意:这边的"en-us.xaml"其实是一个路径

如下所示

生成界面

然后接下来增加窗体添和控件

代码如下

<Window x:Class="WPFMultipleLanguage.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPFMultipleLanguage"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <StackPanel.Resources>
            <Style TargetType="Button">
                <Setter Property="Width" Value="120"></Setter>
                <Setter Property="Height" Value="25"></Setter>
            </Style>
        </StackPanel.Resources>
        <Button Content="中文"></Button>
        <Button Content="英语"></Button>
        <Button Content="{DynamicResource OK}"></Button>
        <Button Content="{DynamicResource Cancle}"></Button>
    </StackPanel>
</Window>

注意:最后两个按钮一定要用DynamicResource绑定,绑定到资源

配置设置

配置设置的目的是为了保留语言设置

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

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="Language" value="en-us" />
  </appSettings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
</configuration>

后台代码实现

添加引用

打开App.xaml的后台代码,添加UpdateLanguage(string lan)方法

using System.Configuration;
using System.Linq;
using System.Windows;

namespace WPFMultipleLanguage
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        //更换语言
        public static void UpdateLanguage(string lan)
        {
            // 获取配置
            string requestedLanguage = $"{lan}.xaml";
            ResourceDictionary resourceDictionary = Application.Current.Resources.MergedDictionaries.FirstOrDefault(d => d.Source.OriginalString.Equals(requestedLanguage));
            Current.Resources.MergedDictionaries.Remove(resourceDictionary);
            Current.Resources.MergedDictionaries.Add(resourceDictionary);

            // 保存配置
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ConfigurationManager.AppSettings["Language"] = lan;
            config.Save(ConfigurationSaveMode.Modified);
            //刷新
            ConfigurationManager.RefreshSection("appSettings");
        }
    }
}

到MainWindow.xaml前端代码,给两个按钮增加事件

<Button Content="中文" Click="Button_Click"></Button>
<Button Content="英语" Click="Button_Click_1"></Button>

事件对应的后台代码如下

using System.Windows;

namespace WPFMultipleLanguage
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            App.UpdateLanguage("zh-cn");
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            App.UpdateLanguage("en-us");
        }
    }
}

完成之后运行代码,就可以看到多语音切换的效果了

项目源码

gitee.com/chenheze90/…

最后

如果你觉得这篇文章对你有帮助,不妨点个赞支持一下!你的支持是我继续分享知识的动力。如果有任何疑问或需要进一步的帮助,欢迎随时留言。

也可以加入微信公众号 [DotNet技术匠] 社区,与其他热爱技术的同行一起交流心得,共同成长!

优秀是一种习惯,欢迎大家留言学习!

作者:Chenhz09

出处:blog.csdn.net/magicchz/article/details/131435511

声明:网络内容,仅供学习,尊重版权,侵权速删,歉意致谢!