WPF通过资源字典实现语言切换

本文将介绍通过资源字典的方式来动态地实现语言切换功能。其本质是在需要显示不同语言时,使用不同的字符串资源文件。

代码收入于Simple-WPF仓库中

也可以通过这个直达链接进行访问。

Fa920y0UexfaWpalYOzneWK3N-7W0PBs3GaIqfsw63k.gif

创建两个资源文件来储存不同语种的字符串,然后直接在界面文件中调用对应的资源。切换不同的显示语种时,仅切换调用的资源文件即可。

tZfdqBazr_9G1bjeda5EjwnjmCK44HLnaBZ66UW6RTE.png
需要注意的是,界面文件中需要使用DynamicResource 关键字。如果使用StaticResource 关键字引用资源,切换资源字典后并不会生效修改。

<Window x:Class="LocalizationWithDynamicXamlResource.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:LocalizationWithDynamicXamlResource"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resources/style.xaml"/>
                <ResourceDictionary Source="Resources/en.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <Button x:Name="BtnChinese" Grid.Column="0" Click="BtnChinese_Click" Content="{DynamicResource ResourceKey=StrToZh}"/>
        <Button x:Name="BtnEnglish" Grid.Column="1" Click="BtnEnglish_Click" Content="{DynamicResource ResourceKey=StrToEn}"/>
    </Grid>
</Window>

切换资源的代码如下,需要注意的是对URI的需要遵照Pack URIs in WPF中介绍的规则进行编写

private void BtnChinese_Click(object sender, RoutedEventArgs e)
{

    Resources.MergedDictionaries.Clear();
    ResourceDictionary styleDictionary = new ResourceDictionary();
    styleDictionary.Source = new Uri("pack://application:,,,/Resources/style.xaml");
    ResourceDictionary langDictionary = new ResourceDictionary();
    langDictionary.Source = new Uri("pack://application:,,,/Resources/zh.xaml");
    Resources.MergedDictionaries.Add(styleDictionary);
    Resources.MergedDictionaries.Add(langDictionary);
}

private void BtnEnglish_Click(object sender, RoutedEventArgs e)
{
    Resources.MergedDictionaries.Clear();
    ResourceDictionary styleDictionary = new ResourceDictionary();
    styleDictionary.Source = new Uri("pack://application:,,,/Resources/style.xaml");
    ResourceDictionary langDictionary = new ResourceDictionary();
    langDictionary.Source = new Uri("pack://application:,,,/Resources/en.xaml");
    Resources.MergedDictionaries.Add(styleDictionary);
    Resources.MergedDictionaries.Add(langDictionary);

}

参考链接

  1. Pack URIs in WPF
  2. 如何:使用 ResourceDictionary 来管理可本地化的字符串资源
  3. 如何:使用 ResourceDictionary 来管理可本地化的字符串资源
  4. How to change ResourceDictionary Dynamically