WPF实现语言切换

本示例实现的是中英文语言切换。

开发环境:VS2022、WIN10

 

一、新建中英文两个key-value对照文件。

 

二、添加到App.xaml文件。

 

三、在App.xaml代码文件中创建切换语言和根据key获取value值的方法。

复制代码
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;

namespace LangSwitch
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        public static ResourceDictionary resourceDictionary;

        public App()
        {

        }

        //更换语言
        public static bool UpdateLanguage(string lan)
        {
            bool res = false;

            // 获取配置
            string requestedLanguage = $"{lan}.xaml";
            resourceDictionary = Application.Current.Resources.MergedDictionaries.FirstOrDefault(d => d.Source.OriginalString.Equals(requestedLanguage));

            if (resourceDictionary != null)
            {
                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");

                res = true;
            }

            return res;
        }

        public static string GetText(string key)
        {
            string res = string.Empty;

            if (resourceDictionary != null)
            {
                var dictionary = resourceDictionary.Cast<DictionaryEntry>();
                var item = dictionary.FirstOrDefault(r => r.Key.ToString() == key);
                if (item.Value != null)
                {
                    res = item.Value.ToString();
                }
                else
                {
                    res = "key搞错了";
                }
            }

            return res;
        }

        
    }
}
复制代码

 

四、为中英文key-value对照文件添加一些数据。

 

 

五、在主界面MainWindow.xaml添加语言切换的应用。

复制代码
<Window x:Class="LangSwitch.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:LangSwitch"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
    <Grid>
        <StackPanel Orientation="Vertical">
            <Button Height="25" Content="{DynamicResource 确定}" Click="Button_OkClick"></Button>
            <Button Height="25" Content="{DynamicResource 取消}" Click="Button_CancelClick"></Button>
            <ComboBox Height="25" Name="LangList" SelectionChanged="LangList_SelectionChanged"></ComboBox>
        </StackPanel>
    </Grid>
</Window>
复制代码
复制代码
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

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

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var langList = new List<string>();
            langList.Add("中文");
            langList.Add("English");
            LangList.ItemsSource = langList;
            LangList.SelectedIndex = 0;

        }

        private void LangList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (LangList.SelectedItem != null)
            {
                if (LangList.SelectedItem.ToString() == "中文")
                {
                    App.UpdateLanguage("Lang-zh-cn");
                }
                else
                {
                    App.UpdateLanguage("Lang-en-us");
                }

            }
        }

        private void Button_OkClick(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(App.GetText("你点了确定按钮"));
        }

        private void Button_CancelClick(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(App.GetText("你点了取消按钮"));
        }
    }
}
复制代码

 

到这里,WPF实现中英文切换的功能就完成了!如果需要添加其他国家语言也是同理的,添加一个key-value对照文件,在切换语言方法添加一个条件分支即可。

 

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