WPF实现本地化及运行时切换语言

WPF实现本地化及运行时切换语言

添加资源文件

找一个存放本地化资源文件的目录,例如/Resources/Languages目录下.

右键添加资源字典,这里简单命名为Strings.zh-CN.xaml.

添加需要翻译的字段

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

xml
<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">
    <!-- Navigation -->
    <system:String x:Key="Navigation_Home">Home</system:String>
</ResourceDictionary>

本地化管理

新建一个类LanguageService,用于管理本地化语言。

XAML中使用

使用DynamicResource才可以支持运行时动态更新

xml
<ui:Button Content="{DynamicResource Navigation_Home}" />

c#中使用

c#
button.Content = new DynamicResourceExtension("Navigation_Home").ProvideValue(null);

切换语言

c#
LanguageService.ChangeLanguage("en-US");
Android使用uiautomator
WPF创建简单用户控件

评论区

评论加载中...