WPF 实现多语言支持

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、执行以上代码,即可完成切换

引用:https://my.oschina.net/u/4350132/blog/3957434

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值