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

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

zh-cn.xam如下: 

<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>

 

2、讲两个资源字典添加到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>

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

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

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

 

4、动态切换,重新加载资源文件
代码如下:
            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);

 

5、执行以上代码,即可完成切换
posted @ 2016-05-12 09:44  土豆核  阅读(7257)  评论(0编辑  收藏  举报