【问题标题】:Localizing strings in WPF codebehind using XAML ResourceDictionary使用 XAML ResourceDictionary 在 WPF 代码隐藏中本地化字符串
【发布时间】:2012-03-30 22:54:11
【问题描述】:

我正在使用 LocBaml 方法本地化 WPF 应用程序。一切都适用于 .xaml 文件中定义的 UI。但是,我有一些在代码隐藏中生成的字符串也必须本地化。所以我尝试采用微软在this文章中推荐的方法。我有一个这样的 xaml 资源字典文件:

<ResourceDictionary x:Uid="ResourceDictionary_1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:system="clr-namespace:System;assembly=mscorlib">

     <!-- String resource that can be localized -->
     <system:String x:Uid="system:String_1" x:Key="localizedMessage">en-US Message</system:String>
</ResourceDictionary>

然后我使用第三方工具生成包含西班牙语版本的资源字典的本地化 resources.dll。

但是,当我打电话时

string localizedMessage = (string)Application.Current.Resources["localizedMessage"];

localizedMessage 始终返回在 dll 的 en-US 版本中定义的值。我一定是误会了什么。我必须做什么才能获得返回的字符串的本地化版本?

【问题讨论】:

  • 你定义了装配文化吗? (它应该保持中立。)您的主题文化是美国文化还是预期的本地化文化(应该是后者)?如果您从某些 XAML 中引用资源会发生什么? (&lt;Label Text="{DynamicResource localizedMessage}"/&gt;)
  • 顺便说一下,参数x:Uid="system:String_1" x:Key="localizedMessage"应该是一样的,AFAIK。 (即x:Uid="localizedMessage" x:Key="localizedMessage"。)
  • 在我的 AssemblyInfo.cs 中我有 [assembly: NeutralResourcesLanguageAttribute("en-US", UltimateResourceFallbackLocation.Satellite)],并在调用资源时设置断点显示我的线程文化和 uiculture 都设置为“es”
  • string localizedMessage = (string)FindResource("localizedMessage"); 返回什么?
  • (1) 好吧,我最好只留下一个 baml,也许将 dll 分成 2 个。 (4) 字典只加载一次,所以 OnStartup 可能为时已晚。我会尝试将语言设置移动到 App 的构造函数的开头。

标签: wpf xaml localization resourcedictionary


【解决方案1】:

与 OP 讨论后,问题在于设置语言太晚(在AppOnStartup)。

确实,本地化的资源字典被加载一次,使用线程的当前语言。如果线程语言更改得太晚,则资源已经加载,不会触发重新加载。

在这种特殊情况下,一个解决方案是尽早更改 UI 线程的语言环境,即在 App 的构造函数中。

【讨论】:

  • 我发现我必须在应用程序的构造函数中调用 InitializeComponent() 之前设置线程的语言环境。希望这对某人有所帮助。
  • @TomasKohl:确实! InitializeComponent 加载并解释 XAML,因此这可能已经加载了资源字典。
猜你喜欢
  • 2011-04-21
  • 1970-01-01
  • 2011-08-03
  • 1970-01-01
  • 1970-01-01
  • 2013-09-18
  • 1970-01-01
  • 1970-01-01
  • 2012-07-15
相关资源
最近更新 更多