WPF国际化建议使用官方推荐方式,当然也可以通过自己写个类实现,没必要重复造轮子,如下记录过程
添加资源文件
- 新建文件,并按照语言命名
- 适当修改生成文件,添加字符lib
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib"> </ResourceDictionary>
- 开始添加相对应的语言翻译等
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib"> <sys:String x:Key="helpImage">Help</sys:String> </ResourceDictionary>
- 修改文件生成
引用定义的资源
- 首先需要定义默认的资源文件,此处先添加默认资源文件,后面详细说如何引用切换资源文件,在APP.xaml中添加引用资源文件
<Application x:Class="ServoStudio.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ServoStudio"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="lang/EN.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
- xmal中引用资源,使用DynamicResource,后面加上对应的key即可
<Image Name="helpImage" Source="png/description.png" Cursor="Help" ToolTip="{DynamicResource helpImage}"></Image>
- 后台中引用,下面介绍两种方式
在属性中设置,设置label的content
label.SetResourceReference(ContentProperty, "Graph1Lable1");
直接设置,设置label的content
label.Content = App.Current.Resources.MergedDictionaries[0]["updateTrueDButton1"] as string
两种方式的区别这里没有详细比较,可能和切换语言后是否直接可以刷新有关,第一种可以直接刷新,第二种不可以,这里没有做验证,在我的应用中需要加载其他配置文件,所以需要重启后再生效
经测试可不使用MergedDictionaries直接使用
label.Content = App.Current.Resources["updateTrueDButton1"] as string
切换资源文件,即语言修改
前面已经设置了默认语言,但是我们应该包根据设置来选择相关语言,所以需要在后台选择设置资源文件
此处给出我的方式,先清除之前的配置,然后加载进来新的,可根据这个demo修改成选择后调用此方法
private void InitLang()
{
//总体设置
App.Current.Resources.MergedDictionaries.Clear();
ResourceDictionary resourceDictionary = new ResourceDictionary();
switch (Properties.Settings.Default.lang)
{
case "zh-CN":
resourceDictionary.Source = new Uri("lang/zh-CN.xaml", UriKind.Relative);
break;
default:
resourceDictionary.Source = new Uri("lang/zh-CN.xaml", UriKind.Relative);
break;
}
App.Current.Resources.MergedDictionaries.Add(resourceDictionary);
}
一些问题
实际使用过程中发现的几个问题
还有需要注意的是这里使用的方式是直接调用了MergedDictionaries[0],所以需要确保该引用值和里面的对应- 加载的文件注意是添加到App总的资源中,而不是当前页面的资源
可以直接如下引用2020.5.19完善
- App.Current.Resources["String22"] as string
随着认知的增长,今天记录东西到了明天可能我就认为他是错的
闻道有先后。。