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

 

五、執行以上代碼,便可完成切換
相關文章
相關標籤/搜索