WPF 界面实现多语言支持 中英文切换 动态加载资源字典

原文: WPF 界面实现多语言支持 中英文切换 动态加载资源字典

一、使用资源字典,首先新建两个字典文件en-us.xaml、zh-cn.xaml。定义中英文的字符串在这里面【注意:添加xmlns:s="clr-namespace:System;assembly=mscorlib】html

zh-cn.xam以下: spa

<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" xmlns:local="clr-namespace:WpfApplication">
     <s:String x:Key="buttonNewTaskWindow">新建任务</s:String>
     <s:String x:Key="buttonProperty">任务属性</s:String>
< /ResourceDictionary>

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" xmlns:local="clr-namespace:WpfApplication">
     <s:String x:Key="buttonNewTaskWindow">New Task</s:String>
     <s:String x:Key="buttonProperty">Task Property</s:String>

</ResourceDictionary>

 

二、讲两个资源字典添加到App.xaml中,这里注意下,由于两个字典中有一样字符,若是没有动态更改,默认后添加的生效
App.xaml以下:
<Application x:Class="WpfApplication.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\en-us.xaml"/>
                 <ResourceDictionary Source="Resources\zh-cn.xaml"/>
             </ResourceDictionary.MergedDictionaries>
      </ResourceDictionary>
          
     </Application.Resources>
< /Application>

三、在界面设计器中须要显示的位置添加动态资源code

例如:
<Button x:Name="buttonNewTaskWindow" Content="{DynamicResource buttonNewTaskWindow}"/>

<Button x:Name="buttonProperty" Content="{DynamicResource buttonProperty}"/>

 

四、动态切换,从新加载资源文件
代码以下:
List<ResourceDictionary> dictionaryList = new List<ResourceDictionary>(); foreach (ResourceDictionary dictionary in Application.Current.Resources.MergedDictionaries) { dictionaryList.Add(dictionary); } string requestedCulture = @"Resources\en-us.xaml"; ResourceDictionary resourceDictionary = dictionaryList.FirstOrDefault(d => d.Source.OriginalString.Equals(requestedCulture)); Application.Current.Resources.MergedDictionaries.Remove(resourceDictionary); Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);

 

五、执行以上代码,便可完成切换