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. 实现效果

中文版

英文版

相关推荐
weixin1997010801615 小时前
《大促护航:电商API限流与降级,双11峰值500万调用的架构复盘》(附Python源码)
python·架构·wpf
hh9501 天前
gent Plan x DeepSeek Harness:多 Agent 协作场景下的中央编排实践
人工智能·wpf·adg·火山引擎·agent plan·adg成都社区
Vae_Mars2 天前
WPF中的Lazy<T>使用方法
wpf
zQ.ii2 天前
WPF 触发器学习笔记
笔记·学习·wpf
SamChan902 天前
用PostgreSQL+pgvector构建PDF翻译记忆库:向量相似度检索+增量更新实战
数据库·python·ai·postgresql·pdf·wpf
李高钢3 天前
开源控件库 HandyControl 介绍与简单实践:让 WPF 界面告别“上个世纪“
开源·wpf
旋生万物3 天前
【终极实战】用Python从零“生成“一个宇宙:螺旋干涉模型的代码实现
开发语言·前端·人工智能·react.js·php·wpf
Now喔4 天前
WPF画刷介绍
wpf
李高钢4 天前
WPF/WinForms 客户端通过 gRPC 与后端通信:从 Proto 契约到流式调用的完整指南
wpf·grpc·winforms
一见已难忘5 天前
基于 Harmony 6.0 应用的宠物寄养预约系统实现
wpf·宠物