WPF 多语言实现

界面应用:

 <Label x:Name="color" Content="{DynamicResource ColorCoding}" VerticalAlignment="Center"/>

 <Label x:Name="Mask" Content="{DynamicResource MaskColor}" VerticalAlignment="Center"/>

 <Label x:Name="Light" Content="{DynamicResource LightColor}" VerticalAlignment="Center"/>

 <Label x:Name="FontSizes" Content="{DynamicResource FontSize}" VerticalAlignment="Center"/>

..................................................

所有的界面上的文字,都使用DynamicResource引用资源文件中的字符串。资源文件en-us.xaml的格式如下(英文资源文件示例):

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:System;assembly=mscorlib">
<s:String x:Key="ColorCoding">ColorCoding:</s:String>
<s:String x:Key="MaskColor">MaskColor:</s:String>
<s:String x:Key="LightColor">LightColor:</s:String>
<s:String x:Key="FontSize">FontSize:</s:String>
</ResourceDictionary>

中文资源文件zh-cn.xaml只要改成中文就OK:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:System;assembly=mscorlib">
<s:String x:Key="ColorCoding">颜色编码:</s:String>
<s:String x:Key="MaskColor">表面色彩:</s:String>
<s:String x:Key="LightColor">灯光色彩:</s:String>
<s:String x:Key="FontSize">字体大小:</s:String>
</ResourceDictionary>

App.xaml文件中设置Application的默认加载语言的方式:

<Application x:Class="SurfacePlotDemo.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="Resources/DemoWindowStyles.xaml"/>//1、2两个资源自己引用的,与程序无关。
<ResourceDictionary Source="Resources/Windows.xaml"/>
<ResourceDictionary Source="Resources/en-us.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>

如何运行时切换语言的呢?只要把上面代码里的ResourceDictionary替换掉就OK了,界面会自动刷新。下面就是实现替换功能的代码。

using System.Windows;

namespace *********
{
  public class LanguageHelper
  {
    public void LoadLanguageFile(string languagefileName)
    {
      Application.Current.Resources.MergedDictionaries[2] = new ResourceDictionary()//此处【2】是因为资源中语言放在第三个。
      {
        Source = new Uri(languagefileName, UriKind.RelativeOrAbsolute)
      };
    }
  }
}

参数languagefileName可以是文件的绝对路径,如:C:en-US.xaml或是和App.xaml里一样的相对路径。

以目前的测试结果来看,即使界面上有大量的细粒度文字。切换语言的速度也是一瞬间的事儿,如果慢,也是因为xaml文件过大,读文件用了不少时间。

 

最后在主界面中用两个按钮控制切换语言:

private void EnglishButtonClick(object sender, RoutedEventArgs e)
{
LanguageHelper lh1 = new LanguageHelper();
string s = "Resources/en-us.xaml";
lh1.LoadLanguageFile(s);
}
private void ChineseButtonClick(object sender, RoutedEventArgs e)
{
LanguageHelper lh2 = new LanguageHelper();
string s2 = "Resources/zh-cn.xaml";
lh2.LoadLanguageFile(s2);
}

这样就完成啦!

原文地址:https://www.cnblogs.com/syqun/p/language.html