此示例演示如何使用一个 ResourceDictionary 来打包 Windows Presentation Foundation (WPF) 应用程序的可本地化的字符串资源。
使用 ResourceDictionary 管理可本地化的字符串资源
在名为 ResourceDictionary 的项目根目录中创建一个文件,其中包含要本地化的字符串。 以下代码展示了一个示例。
<ResourceDictionary 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:Key="localizedMessage">en-US Message</system:String> </ResourceDictionary>
该代码在 mscorlib.dll的
localizedMessage
命名空间中定义一个字符串资源 String,其类型为 System。将 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);
' Programmatic use of string resource from StringResources.xaml resource dictionary Dim localizedMessage As String = CStr(Application.Current.FindResource("localizedMessage")) MessageBox.Show(localizedMessage)
本地化应用程序。 有关详细信息,请参阅 本地化应用程序。