我正在对 WPF 中的 GUI 进行本地化。我在这里发布的代码将来自原型(prototype),因为我试图让这个问题尽可能简单。
我正在使用资源字典在我的窗口中设置字符串的内容。我有两个,一个是德语,一个是英语。
德语资源词典:
<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">
<!-- The name of this ResourceDictionary. Should not be localized. -->
<sys:String x:Key="ResourceDictionaryName" Localization.Comments="$Content(DoNotLocalize)">Loc-de-DE</sys:String>
<!--- Button -->
<sys:String x:Key="MainButton_Title">Hallo Welt!</sys:String>
<sys:String x:Key="EnglishButton">Englisch</sys:String>
<sys:String x:Key="GermanButton">Deutsch</sys:String>
</ResourceDictionary>
英语资源词典:
<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">
<!-- The name of this ResourceDictionary. Should not be localized. -->
<sys:String x:Key="ResourceDictionaryName" Localization.Comments="$Content(DoNotLocalize)">Loc-en-US</sys:String>
<!--- Buttons -->
<sys:String x:Key="MainButton_Title">Hello World!</sys:String>
<sys:String x:Key="EnglishButton">English</sys:String>
<sys:String x:Key="GermanButton">German</sys:String>
</ResourceDictionary>
我还在 XAML 窗口中动态设置了按钮的内容:
<Button Content="{DynamicResource MainButton_Title}" Margin="59,68,0,80" Name="button1" HorizontalAlignment="Left" Width="152" />
<Button Content="{DynamicResource EnglishButton}" Height="23" HorizontalAlignment="Right" Margin="0,83,87,0" Name="button2" VerticalAlignment="Top" Width="75" Click="button2_Click" />
<Button Content="{DynamicResource GermanButton}" Height="23" HorizontalAlignment="Right" Margin="0,0,87,90" Name="button3" VerticalAlignment="Bottom" Width="75" />
我希望在单击英语按钮时将语言更改为英语,并在单击德语按钮时更改为德语。我已经做到了这一点,但我不知道告诉程序更改它的资源字典所需的实际代码。我猜这将在两个按钮的单击事件下的代码隐藏中进行,并且可能在 XAML 窗口中也有一些代码。
这些是我使用过的资源,但我发布这个问题是因为最终解决方案对我来说不够清楚:
- http://www.wpfsharp.com/2012/01/27/how-to-change-language-at-run-time-in-wpf-with-loadable-resource-dictionaries-and-dynamicresource-binding/
- http://msdn.microsoft.com/en-us/library/bb613547.aspx
- http://blogs.msdn.com/b/wpfsldesigner/archive/2010/06/03/creating-and-consuming-resource-dictionaries-in-wpf-and-silverlight.aspx
感谢您的帮助!
最佳答案
您应该创建新的资源字典,然后您应该与当前字典合并:
ResourceDictionary dict = new ResourceDictionary();
dict.Source = new Uri("..\\Languages\\EnglishLang.xaml", UriKind.Relative);
this.Resources.MergedDictionaries.Add(dict);
如果要将语言更改为德语,则应在第二行更改文件名。
在我的示例中,您的资源字典应位于 Languages 文件夹中。
检查我在这个问题中的答案:
How to start an internationalized WPF-Project in SharpDevelop 4.2?
关于wpf - 如何正确更改资源字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17552804/