问题描述
根据this tutorial,我尝试为WPF .NET Core 3.1应用程序实现多语言系统。如果我直接更改Title
元素的属性Window
,一切都会正常,应用程序会从相应的资源文件中读取数据,该文件是通过更改CurrentUICulture
来定义的。
以下是更改代码:
private void BtnChangeLanguagetoCsCz_Click(object sender,RoutedEventArgs e)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("cs-CZ");
}
private void BtnChangeLanguagetoEnUs_Click(object sender,RoutedEventArgs e)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
}
但是,当我单击这些按钮中的任何一个之后,它们的内容仍未更新。我觉得我需要调用一些UI更新函数或类似的东西,但到目前为止找不到任何相关的东西。
这是如何绑定Content
的{{1}}属性:
Button
我应该怎么做才能使其自身更新?
解决方法
A找到了基于this教程的解决方案,它没有使用线程的区域性或resource.resx文件,而是使用XAML资源字典。
这可以根据您的情况进行更改,但是,我是针对MainWindow.xaml这样做的:
- 我在名为
Private Sub btnCancel_Click() 'DOES NOT WORK: DoCmd.Close acForm,"Form_Authentication Required" End Sub Private Sub btnCancel_Click() 'DOES NOT WORK EITHER: DoCmd.Close acDialog,"Form_Authentication Required" End Sub
的文件夹中创建了两个资源字典,分别称为“ MainWindow.en-GB.xaml”和“ MainWindow.cs-CZ.xaml”。 - 然后将构建操作设置为
/Resources
,将“复制到输出目录”设置为Content
。 - 创建资源字典后,我创建了一个名为
Copy if newer
的示例资源:
Text
- 然后在MainWindow.xaml中,添加以下代码:
<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="Text">Hello</sys:String>
</ResourceDictionary>
- 接着,将按钮的内容设置为资源
<Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Resources/MainWindow.en-GB.xaml"></ResourceDictionary> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Window.Resources>
:
Text
- 最后,通过使用linked tutorial中的
<Button x:Name="BtnInstall" Content="{DynamicResource ResourceKey=Text}" HorizontalAlignment="Center" Margin="0,324,0" VerticalAlignment="Top" Height="50" Width="200" Click="BtnInstall_Click" />
,调用LocUtil
方法,我可以在两者之间进行切换:
LocUtil.SwitchLanguage