代码片段C#WPFWPF实现本地化及运行时切换语言
钱涛添加资源文件
找一个存放本地化资源文件的目录,例如/Resources/Languages
目录下.
右键添加资源字典
,这里简单命名为Strings.zh-CN.xaml
.
添加需要翻译的字段
1 2 3 4 5 6 7
| <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:system="clr-namespace:System;assembly=mscorlib"> <system:String x:Key="Navigation_Home">主页</system:String> </ResourceDictionary>
|
再新建另一种语言的资源字典,例如Strings.en-US.xaml
.
1 2 3 4 5 6 7
| <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:system="clr-namespace:System;assembly=mscorlib"> <system:String x:Key="Navigation_Home">Home</system:String> </ResourceDictionary>
|
本地化管理
新建一个类LanguageService
,用于管理本地化语言。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public static class LanguageService { private static ResourceDictionary _currentDictionary;
public static void ChangeLanguage(string languageCode) { string path = $"pack://application:,,,/TWPFX_Gallery;component/Resources/Languages/Strings.{languageCode}.xaml";
if (_currentDictionary != null) { Application.Current.Resources.MergedDictionaries.Remove(_currentDictionary); }
_currentDictionary = new ResourceDictionary { Source = new Uri(path) }; Application.Current.Resources.MergedDictionaries.Add(_currentDictionary); }
public static void Initialize() { string sysLang = CultureInfo.CurrentCulture.Name; ChangeLanguage(sysLang == "zh-CN" ? "zh-CN" : "en-US"); } }
|
XAML中使用
使用DynamicResource
才可以支持运行时动态更新
1
| <ui:Button Content="{DynamicResource Navigation_Home}" />
|
C#中使用
1
| button.Content = new DynamicResourceExtension("Navigation_Home").ProvideValue(null);
|
切换语言
1
| LanguageService.ChangeLanguage("en-US");
|