WPF页面 全球化和本地化

时间:2022-01-11 15:41:11

传统的 新建.resx类型的文件中,然后利用ResourceManager来得到相应资源并根据当地的CultureInfo来给界面文本赋值。

WPF

新建一个文件夹 Language

新建2个资源字典。

DefaultLanguage.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<sys:String x:Key="OK">
OK
</sys:String> <sys:String x:Key="Cancel">
Cancel
</sys:String>
</ResourceDictionary>

zh-CN.xaml

<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"> <sys:String x:Key="OK">
确定
</sys:String> <sys:String x:Key="Cancel">
取消
</sys:String> </ResourceDictionary>

App.xaml 引入路径

<Application x:Class="WpfApplication1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml"> <Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Language\DefaultLanguage.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary> </Application.Resources>
</Application>

App.cs代码:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Globalization; namespace WpfApplication1
{
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
LoadLanguage();
} private void LoadLanguage()
{
CultureInfo currentCultureInfo = CultureInfo.CurrentCulture;
ResourceDictionary langRd = null; try
{
langRd = Application.LoadComponent(new Uri(string.Format("{0}{1}.xaml", "Language\\", currentCultureInfo.Name), UriKind.Relative)) as ResourceDictionary;
}
catch
{
} if (langRd != null)
{
if (this.Resources.MergedDictionaries.Count > )
{
this.Resources.MergedDictionaries.Clear();
}
this.Resources.MergedDictionaries.Add(langRd);
} }
}
}

页面使用:

            <Button Content="{DynamicResource OK}"/>
<Button Content="{DynamicResource Cancel}"/>