【保存版】CommunityToolkit.MvvmでDIを利用した、実務的なWPFでの国際化対応(多言語対応)

DIを使いながら、国際化対応(多言語対応)をしよう 今やグローバル時代!世界を相手にしなければ勝てない! そう、東京弁だけでなく大阪弁、名古屋弁、博多弁など…ごめんなさい調子に乗りました、単純に「日本語」「英語」「ロシア語」対応について語ります。(天丼) 今回は総集編として カップ麺シリーズ:一から学べる、WPFでの多言語対応方法 を、DI込みの記事として公開します。 最初にプロジェクトを作ろう 今回は「WPFアプリケーション」で DIMultiLanguageTest というプロジェクトを作りましょう。フレームワークは「.NET 9.0」を利用します。 プロジェクトに Views と ViewModel フォルダを作ります。 そして開かれた MainWindow.xaml を Views フォルダに移動して、以下のようにします。 <Window x:Class="DIMultiLanguageTest.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:local="clr-namespace:DIMultiLanguageTest" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Title="DIMultiLanguageTest" Width="800" Height="450" mc:Ignorable="d"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Menu> <MenuItem Header="Language"> <MenuItem Command="{Binding ToJapaneseCommand}" Header="Japanese" /> <MenuItem Command="{Binding ToEnglishCommand}" Header="English" /> <MenuItem Command="{Binding ToRussianCommand}" Header="Russian" /> </MenuItem> </Menu> <Button Grid.Row="1" Margin="5" Command="{Binding ExecuteGreetingsCommand}" Content="{Binding Greetings}" /> </Grid> </Window> MainWindow.xaml のフォルダを移動したので、このままでは例外で落ちるため、App.xaml を以下のように書き換えます。 <Application x:Class="DIMultiLanguageTest.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:DIMultiLanguageTest" StartupUri="Views/MainWindow.xaml"> <Application.Resources /> </Application> わかると思いますが、MainWindow.xaml を移動した Views\ を StartupUri に書き加えたわけですね。 ...

2025年04月11日 · (2025年04月30日 更新) · 3 分 · もりゃき