WPF使用内置资源系统实现国际化

使用WPF内置资源系统实现国际化

1.创建资源字典文件

创建

在资源Resources文件夹下创建语言的资源字典文件

创建资源字典

编写语言内容

首先引入System命名空间,后续资源都是string类型

xmlns:sys="clr-namespace:System;assembly=mscorlib"

然后添加对应的字符串,key和对应的文本,在不同语言中Key需要一一对应,然后文本是不同语言的。

示例如下

中文Lang.zh-CN.xaml

XML 复制代码
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <sys:String x:Key="Title_MainWindow">主窗口</sys:String>
    <sys:String x:Key="Button_Save">保存</sys:String>
    <sys:String x:Key="Menu_File">文件</sys:String>
    <sys:String x:Key="Menu_Edit">编辑</sys:String>
    <sys:String x:Key="Button_CN">中文版</sys:String>
    <sys:String x:Key="Button_EN">英文版</sys:String>

</ResourceDictionary>

英文 Lang.en-US.xaml

XML 复制代码
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <sys:String x:Key="Title_MainWindow">Main Window</sys:String>
    <sys:String x:Key="Button_Save">Save</sys:String>
    <sys:String x:Key="Menu_File">File</sys:String>
    <sys:String x:Key="Menu_Edit">Edit</sys:String>
    <sys:String x:Key="Button_CN">Chinese</sys:String>
    <sys:String x:Key="Button_EN">English</sys:String>
</ResourceDictionary>

其他语言

按同样形式添加

2. 创建资源管理类

csharp 复制代码
using System.Globalization;
using System.Windows;
using System.Windows.Markup;

public static class LanguageManager
{
    private static ResourceDictionary? _currentResourceDictionary;

    public static event EventHandler? LanguageChanged;

    public static CultureInfo CurrentCulture { get; private set; } = CultureInfo.CurrentCulture;

    // 支持的语言列表
    public static List<CultureInfo> SupportedLanguages { get; } = new()
    {
        new CultureInfo("en-US"),
        new CultureInfo("zh-CN"),
        new CultureInfo("ja-JP")
    };

    public static void ChangeLanguage(CultureInfo culture)
    {
        if (culture == null) throw new ArgumentNullException(nameof(culture));

        CurrentCulture = culture;
        
        // 设置当前线程的UICulture
        Thread.CurrentThread.CurrentUICulture = culture;
        Thread.CurrentThread.CurrentCulture = culture;
        
        // 加载对应的资源字典
        LoadResourceDictionary(culture.Name);
        
        LanguageChanged?.Invoke(null, EventArgs.Empty);
    }

    private static void LoadResourceDictionary(string languageCode)
    {
        var app = Application.Current;
        if (app == null) return;

        // 移除现有的语言资源
        if (_currentResourceDictionary != null)
        {
            app.Resources.MergedDictionaries.Remove(_currentResourceDictionary);
        }

        // 加载新的语言资源
        var dict = new ResourceDictionary
        {
            Source = new Uri($"/YourProjectName;component/Resources/Lang.{languageCode}.xaml", 
                           UriKind.RelativeOrAbsolute)
        };

        app.Resources.MergedDictionaries.Add(dict);
        _currentResourceDictionary = dict;
    }

    // 从资源文件中获取字符串(代码中使用)
    public static string GetString(string key)
    {
        var value = Application.Current.TryFindResource(key);
        return value as string ?? $"#{key}#";
    }
}

3. 在XAML中使用

之前直接写文本的地方都通过DynamicResource动态绑定资源名称

csharp 复制代码
<Window
    x:Class="WpfInternationalApp.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:local="clr-namespace:WpfInternationalApp"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Title="{DynamicResource Title_MainWindow}"
    Width="800"
    Height="450"
    mc:Ignorable="d">
    <Grid>
        <Button
            Width="97"
            Height="32"
            Margin="89,126,0,0"
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Click="Button_Click"
            Content="{DynamicResource Button_EN}" />
        <Button
            Width="97"
            Height="32"
            Margin="233,126,0,0"
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Click="Button_Click_1"
            Content="{DynamicResource Button_CN}" />
        <Button
            Width="109"
            Height="30"
            Margin="206,260,0,0"
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Content="{DynamicResource Button_Save}" />
    </Grid>
</Window>

4. 初始化语言设置

方式一:在App.xaml中加载资源

csharp 复制代码
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Resources/Languages/Lang.zh-CN.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

方式二:在App.xaml.cs中加载

csharp 复制代码
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            // 设置框架级别的语言
            FrameworkElement.LanguageProperty.OverrideMetadata(
                typeof(FrameworkElement),
                new FrameworkPropertyMetadata(
                    XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

            // 加载默认语言
            LanguageManager.ChangeLanguage(LanguageManager.SupportedLanguages[0]);
        }

5. 语言切换

直接使用ChangeLanguage方法切换即可

csharp 复制代码
LanguageManager.ChangeLanguage(LanguageManager.SupportedLanguages[0]);
LanguageManager.ChangeLanguage(LanguageManager.SupportedLanguages[1]);

6. 实现效果

中文版

英文版

相关推荐
慧都小妮子15 小时前
SciChart WPF v9.0 更新详解:矢量场图表、堆叠箱线图与 MVVM 轴同步来了
c#·.net·wpf·数据可视化·图表控件·图表
He BianGu21 小时前
【笔记】WPF中 Brush 的类型、继承关系、使用方式和注意事项
笔记·wpf
FuckPatience3 天前
WPF GridView 列绑定时前端没有属性提示
wpf
界面开发小八哥3 天前
界面控件DevExpress WPF v26.1新版亮点 - 模板工具包 & MVVM功能全新升级
wpf·界面控件·devexpress·ui开发·.net 10
记忆停留w5 天前
Celery+Redis 分布式异步任务队列工程落地业务逻辑
大数据·人工智能·redis·分布式·缓存·架构·wpf
雪靡5 天前
WPF PerMonitorV2 下的跨窗口问题
c#·wpf
listening7776 天前
HarmonyOS 6.1 分布式文件服务实战:跨设备商品图片/视频秒开方案
wpf·harmonyos
Macbethad6 天前
基于WPF的半导体设备EAP控制程序架构设计与实现
wpf
国服第二切图仔7 天前
HarmonyOS APP《画伴梦工厂》开发第60篇-分布式软总线2.0——多设备协同新范式
分布式·wpf·harmonyos
精神底层7 天前
拒绝 UI 卡死!我用 CSnakes 实时拦截 Python 训练流,在 WPF 中重构了 ScottPlot 5 高性能 AI 看板
python·ui·wpf