星屿浅奈 ✧ Saneko

Back

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

添加资源文件#

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

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

添加需要翻译的字段

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

再新建另一种语言的资源字典,例如Strings.en-US.xaml.

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

本地化管理#

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

XAML中使用#

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

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

C#中使用#

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

切换语言#

LanguageService.ChangeLanguage("en-US");
c
WPF实现本地化及运行时切换语言
https://saneko.me/blog/ab8de32d8402
Author Saneko
Published at June 18, 2025
Buy me a cup of coffee ☕.
Comment seems to stuck. Try to refresh?✨