【WPF】 热重载切换多语言
如何使用WPF热重载切换语言
一、依赖包
两个依赖包
1.Antelcat.I18N.WPF 网址:https://github.com/XAMLMarkupExtensions/WPFLocalizeExtension
2.WPFLocalizeExtension 网址:https://github.com/Antelcat/I18N?tab=readme-ov-file
二、创建资源文件
ps:项目名字拼写有误——更正为MutilCultureDemo
1.创建Resrouces文件夹,新建资源文件.resx,这个资源浏览器必须是VS202217.10+以上的版本才有,没有就去更新IDE
2.使用先前的.Antelcat.I18N.WPF包动态生成资源键:
using Antelcat.I18N.Attributes;
namespace MultCultrueDemo.Resources;
[ResourceKeysOf(typeof(Lang))] public partial class LangKeys { }
三、Xaml代码
1.引入两个依赖包的命名空间:
xmlns:lang="clr-namespace:MultCultrueDemo.Resources"
xmlns:lex="http://wpflocalizeextension.codeplex.com"
lex:ResxLocalizationProvider.DefaultAssembly="MultCultrueDemo"
lex:ResxLocalizationProvider.DefaultDictionary="Lang"
<Grid> <Grid.Resources> <Style BasedOn="{StaticResource {x:Type Button}}" TargetType="Button"> <Setter Property="Width" Value="120" /> <Setter Property="Height" Value="25" /> <Setter Property="Margin" Value="5" /> </Style> </Grid.Resources> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBlock FontSize="32" Text="{I18N {x:Static lang:LangKeys.MainWindow_WelcomeMessage}}" /> <StackPanel Margin="0,16,0,0" HorizontalAlignment="Center" Orientation="Horizontal"> <Button Width="80" Margin="0,0,5,0" Content="{I18N {x:Static lang:LangKeys.MainWindow_English_Button_Content}}" Tag="en" Click="ChangeLanguage_Click" /> <Button Width="80" Margin="5,0,0,0" Content="{I18N {x:Static lang:LangKeys.MainWindow_Chinese_Button_Content}}" Click="ChangeLanguage_Click" Tag="zh-CN" />
</StackPanel> <Button Margin="0,16,0,0" HorizontalAlignment="Center" Content="{I18N {x:Static lang:LangKeys.MainWindow_ShowMessage_Button_Content}}" Click="Button_Click" /> </StackPanel> </Grid>
绑定语言源:<TextBlock Text="{I18N {x:Static myProject:LangKeys.Language}}"/>
四、后台代码
在xaml.cs中using MultCultrueDemo.Resources;
using System.Globalization; using System.Windows; using System.Windows.Controls; private void ChangeLanguage_Click(object sender, RoutedEventArgs e) { var culture = ((Button)sender).Tag.ToString(); // 接收xaml中Button的Tag属性值 var cultureInfo = new CultureInfo(culture); Thread.CurrentThread.CurrentCulture = cultureInfo; Thread.CurrentThread.CurrentUICulture = cultureInfo; // 更改语言 —— I18NExtension.Culture = new CultureInfo("language code") I18NExtension.Culture = cultureInfo; } private void Button_Click(object sender, RoutedEventArgs e) { MessageBox.Show(Lang.MainWindow_ShowMessage_Button_Content, Lang.Message_Caption, MessageBoxButton.OK); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?