如何:使用 ResourceDictionary 来管理可本地化的字符串资源
更新:2007 年 11 月
本示例演示如何使用 ResourceDictionary 来包装 Windows Presentation Foundation (WPF) 应用程序的可本地化字符串资源。
使用 ResourceDictionary 来管理可本地化的字符串资源
创建一个 ResourceDictionary,其中包含要本地化的字符串。下面的代码提供了一个示例。
<ResourceDictionary xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns:system="clr-namespace:System;assembly=mscorlib"> <!-- String resource that can be localized --> <system:String x:Key="localizedMessage">en-US Message</system:String> </ResourceDictionary>
此代码从 mscorlib.dll 中的 System 命名空间定义了一个类型为 String 的字符串资源 localizedMessage。
使用下面的代码将 ResourceDictionary 添加到应用程序中。
<Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="StringResources.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources>
通过如下所示的可扩展应用程序标记语言 (XAML) 来使用标记中的字符串资源。
<!-- Declarative use of string resource from StringResources.xaml resource dictionary --> <TextBox DockPanel.Dock="Top" Text="{StaticResource localizedMessage}" />
通过如下所示的代码来使用代码隐藏文件中的字符串资源。
// Programmatic use of string resource from StringResources.xaml resource dictionary string localizedMessage = (string)Application.Current.FindResource("localizedMessage"); MessageBox.Show(localizedMessage);
将应用程序本地化 有关更多信息,请参见如何:对应用程序进行本地化。
有关此示例的完整源代码,请参见实现 XAML 中的可本地化字符串资源示例。