本ブログはアフィリエイト広告を利用しています。

WPFで多言語化対応(ローカライズ)する

Resource Dictionary プログラミング

WPFでアプリを作成する場合、多言語対応が必要な場合があります。
多言語化には複数の方法がありますが、ここではResourceDictionaryを使用して実装していきます。

リソースファイル(xaml)を言語ごとに作成する

まず、言語ごとにリソースファイルを作成する必要があります。ここでは、日本語と英語の2つの言語を例に説明します。
Resourcesフォルダを作成し、右クリックして「追加 -> リソースディクショナリ」を選択します。
ファイル名は、Dictionary.ja.xamlとします。en(英語)やfr(フランス語)などの言語コードをjaの部分に変更して作成します。
言語コードのjaをja-JPとしても良いですが、後々の処理(使用リソースの振り分け処理)に影響するので変更する場合は注意してください。
最後に作成した各リソースファイルのプロパティから”出力ディレクトリにコピー”を常にコピーする、または新しい場合にコピーするに変更してください。
これを設定しないとIOException(リソース ‘resources/dictionary.ja-jp.xaml’ を検索できません。)が出ます。

Dictionary.ja.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="label_content">日本語</system:String>
</ResourceDictionary>

Dictionary.en.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="label_content">English</system:String>
</ResourceDictionary>
Resource Dictionary

App.xamlにResourceDictionaryの設定を追加する

追加するのは8~12行目となります。
enのリソースファイルを指定していますが、これは例えばフランス語の利用者だがfrのリソースファイルは用意していないので見つからない、という場合に日本語より英語が表示されたほうがいいだろうという配慮です。もちろんここは英語でなければならないということはないのでお好きな言語リソースファイルに変更して構いません。

<Application x:Class="localization.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:localization"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <!--ここ-->
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Resources/Dictionary.en.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

画面xamlを修正

サンプルのためラベルのみの画面となります。
{DynamicResource XXX}で各リソースに定義されたXXXをキーに値を取得してきます。
今回でいうとリソースファイルのlabel_contentには”日本語”、または”English”という文字列を定義しているのでどちらかがLabelで表示されます。

<Window x:Class="localization.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:localization"
mc:Ignorable="d"
Title="MainWindow" Height="100" Width="200">
<StackPanel>
<!-- ここ -->
<Label Content="{DynamicResource label_content}"></Label>
</StackPanel>
</Window>

使用するリソースファイルの振り分け

最後にどのリソースファイルを使用するのかを設定する処理を書いていきます。
以下のソースにある通り、CultureInfo.CurrentUICulture.TwoLetterISOLanguageNameで現在の言語コード(ja,en)を取得し、@$”Resources/Dictionary.{cultureCode}.xaml”とすることでリソースファイルの読み込み先を動的に変更しています。
ja-JPのようにした場合はCultureInfo.CurrentUICultureに処理を変更してください。

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace localization
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            // ここ
            var cultureCode = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;  // ja, en, etc...
            // var cultureCode = CultureInfo.CurrentUICulture;  // ja-JP, en-US, etc...
            var dictionary = new ResourceDictionary();
            try
            {
                var uri = @$"Resources/Dictionary.{cultureCode}.xaml";
                dictionary.Source = new Uri(uri, UriKind.Relative);
                this.Resources.MergedDictionaries.Add(dictionary);
            }
            catch (IOException e)
            {
                // 読み込むリソースファイルがない場合のエラーは無視する
                // App.xamlの<ResourceDictionary Source=""/>で設定してある言語ファイルをそのまま使用する
            }
        }
    }
}

複数画面ある場合は各画面で実装しないといけないかも?

実行結果

日本語、英語それぞれの実行結果が以下です。

lang ja
lang en

PCの言語変更方法

スタートメニューから設定 -> 時刻と言語 -> 左のメニューから言語を選択します。
Windowsの表示言語のプルダウンから英語を選択するとCultureInfo.CurrentUICulture.TwoLetterISOLanguageNameでenが取得できるようになります。
プルダウンに英語がない場合は下の方にある言語の追加でEnglish (United States)を選択し、ダウンロードが完了すると選択できるようになります。
なお、言語の変更はサインアウトが必要となります。

以上です。

関連記事

コメント

タイトルとURLをコピーしました