WPF multi-language support: simple and flexible dynamic switching, allowing your program to support multiple languages

Overview: This sample demonstrates the detailed steps to implement multi-language support in a WPF application. Applications can dynamically switch languages ​​at runtime through resource dictionaries and data binding, as well as using language manager classes. This approach makes multi-language support more flexible and easier to maintain while providing a clear code structure.

A common way to implement multilingualism in WPF is to use resource dictionaries and data binding. Below is a detailed step-by-step and sample source code that demonstrates how to implement dynamic language switching in a WPF application. Code download is provided at the end of the article.

Let’s look at the effect first:

Step 1: Prepare resource files

First, create a resource file for each language. The naming convention for resource files is Resources.{language code}.xaml . For example, Resources.en-US.xaml represents an English (United States) resource file.

In each resource file, add key-value pairs ( in this case, the prefix is ​​the form name to avoid the problem of different forms having the same name ), representing localized strings of different controls or texts. For example:

<!-- Resources.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=netstandard">
    <system:String x:Key="MainWindow_name">Name</system:String>
    <system:String x:Key="MainWindow_age">Age</system:String>
    <system:String x:Key="MainWindow_Language">简体中文</system:String>
</ResourceDictionary>

<!-- Resources.zh-Hans.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=netstandard">
    <system:String x:Key="MainWindow_name" >姓名</system:String>
    <system:String x:Key="MainWindow_age">年龄</system:String>
    <system:String x:Key="MainWindow_Language">English</system:String>
</ResourceDictionary>

Step 2: Create language manager class

Create a language manager class to switch the language of the current application. This class may contain a property representing the current CultureInfo , and a method to switch languages.

using System;
using System.Globalization;
using System.Windows;

public static class LanguageManager
{
    private static ResourceDictionary currentLanguage;

    public static ResourceDictionary CurrentLanguage
    {
        get { return currentLanguage; }
        set
        {
            if (currentLanguage != value)
            {
                currentLanguage = value;
                UpdateLanguage();
            }
        }
    }

    private static void UpdateLanguage()
    {
        if (Application.Current.Resources.MergedDictionaries.Contains(currentLanguage))
        {
            Application.Current.Resources.MergedDictionaries.Remove(currentLanguage);
            Application.Current.Resources.MergedDictionaries.Add(currentLanguage);
        }
        else
        {
            Application.Current.Resources.MergedDictionaries.Add(currentLanguage);
        }
    }
}

Step 3: Using resource dictionaries and data binding in WPF applications

In a XAML file, use Binding to bind the control’s content or text to the corresponding key in the resource dictionary. For example:

<Window x:Class="Sample_LanguageManager.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:Sample_LanguageManager"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.Background>
            <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
                <LinearGradientBrush.GradientStops>
                    <GradientStop Color="#FF9DC5FD" Offset="0" />
                    <GradientStop Color="#FF4242CF" Offset="1" />
                </LinearGradientBrush.GradientStops>
            </LinearGradientBrush>
        </Grid.Background>
        <Grid.RowDefinitions>
            <RowDefinition Height="90"/>
            <RowDefinition Height="60"/>
            <RowDefinition Height="60"/>
        </Grid.RowDefinitions>
        <Label Grid.Row="0"  Content="{DynamicResource MainWindow_name}" d:Content="姓名" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="36" Foreground="White" />
        <Label Grid.Row="1" Content="{DynamicResource MainWindow_age}" d:Content="年龄" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="36" Foreground="White" />
        <Button Grid.Row="2" Content="{DynamicResource MainWindow_Language}" d:Content="切换语言" Click="SwitchToFrench_Click" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="22"/>
    </Grid>
</Window>

Step 4: Set the language when the application starts

On application startup, set the LanguageManager ‘s CurrentLanguage property to select the initial language. This can be done in the OnStartup method in App.xaml.cs.

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        // 设置初始语言,例如英语
        LanguageManager.CurrentLanguage = new ResourceDictionary { Source = new Uri("Resources.en-US.xaml", UriKind.Relative) };

        // 其他启动逻辑...

        base.OnStartup(e);
    }
}

Step 5: Implement language switching

You can provide users with the option to switch languages ​​somewhere in your application. In the language switching event, update the CurrentLanguage property of LanguageManager (because this is a simple example, only Chinese and English switching is provided, but more language dictionaries can actually be provided for switching).

        private void SwitchToFrench_Click(object sender, RoutedEventArgs e)
        {
            if (LanguageManager.CurrentLanguage.Source.OriginalString.Contains("en-US"))
            {
                LanguageManager.CurrentLanguage = new ResourceDictionary { Source = new Uri("Resources.zh-Hans.xaml", UriKind.Relative) };
            }
            else
            {
                LanguageManager.CurrentLanguage = new ResourceDictionary { Source = new Uri("Resources.en-US.xaml", UriKind.Relative) };
            }
        }

Through the above steps, your WPF application can support multiple languages ​​and can dynamically switch languages ​​at runtime. This approach provides flexibility and makes it easy to maintain and manage multilingual applications.