【发布时间】:2013-10-03 11:27:52
【问题描述】:
我正在使用 WPF 创建一个多语言应用程序。我正在使用静态资源,存储在 .resx/res 文件中的字符串以使文本出现在用户的文化中。
这是项目目录结构的一部分:
- 资源
- GreetingWindowRes.resx(这是默认值,适用于 en-US)
- GreetingsWindowRes.de-DE.resx
在 .csproj 中,我有:<UICulture>en-US</UICulture>
在 AssemblyInfo.cs 中:[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
编译后可以看到资源文件出现了:
- zh-CN / MyApp.resources.dll
- de-DE / MyApp.resources.dll
所以我绑定到 GreetingWindow.xaml 中的静态字符串资源:
<windows:MyWindowBase x:Class="CommanderDotNET.MyApp.Windows.GreetingWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:windows="clr-namespace:MyApp.Windows"
xmlns:res="clr-namespace:MyApp.Resources">
<Label Content="{x:Static res:GreetingWindowRes.FirstGreetingText}" />
</windows:MyWindowBase>
结果让我很困惑:
- 如果 UICulture 设置为 de-DE,则标签文本以德语正确显示。
- 如果 UICulture 设置为 en-US,System.Windows.Markup.StaticExtension 会引发 XamlParseException。 我看到的 XAML 错误一定是原因:
找不到任何适合指定文化的资源或 中立文化。确保 “MyApp.Resources.GreetingWindowRes.en-US.resources”原为 在编译时正确嵌入或链接到程序集“MyApp”中,或者 所需的所有附属程序集都是可加载且完全可加载的 签名。
我做错了什么?
解决方案:
经过大量搜索,我在这里找到了一个很好的解释: http://www.west-wind.com/weblog/posts/2009/Jun/04/Resx-and-BAML-Resources-in-WPF
显然,当使用 UltimateResourceFallbackLocation.Satellite + <UICulture> 时,您需要同时拥有 ResxResource.resx 和 GreetingWindowRes.en-US.resx 文件作为主要语言(讨厌的重复)。
但是,如果你只想使用 Resx 资源,而没有 BAML 本地化,这不是要走的路,情况会好很多。仅使用 Resx 资源的正确方法:
- AssemblyInfo.cs:
[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.MainAssembly)] - .csproj:不要添加
<UICulture> - 资源命名:ResxResource.resx(主要语言)+ ResxResource.de-DE.resx(附加语言)
【问题讨论】:
-
感谢您的解释:)
标签: c# wpf xaml localization resx