現在の言語の設定にかかわらず、指定した言語のリソースを取ってくる

もくじ
https://tera1707.com/entry/2022/02/06/144447

やりたいこと

以前の記事で、Windowsの言語設定に合わせてリソースを取得する方法を調べたが、今度は逆に、今現在のWindowsの言語設定によらず、固定である言語の(例えばなんの言語設定にしていても英語の)リソースをコードから取得したい。

やりかた

ResourceManagerResourceContextを使う。

サンプルコード

コード

流れとしては、

  • まずResourceManagerをとってくる。
  • 次に、取ってきたResourceManagerのCreateResourceContext()メソッドで、リソースコンテキストを取ってくる。
  • リソースコンテキストの中のQualifierValueの中の、キーが「Language」であるものに、取得したい言語の言語コードを設定する。
  • manager.MainResourceMap.GetValue()に、リソースの名前と上で作ったリソースコンテキストをセットして呼び出す

ということをすると、指定の言語に該当するリソースを取得できる。

using Microsoft.UI.Xaml;
using Microsoft.Windows.ApplicationModel.Resources;

namespace LaungTest
{
    public sealed partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();

            var manager = new ResourceManager();
            var context = manager.CreateResourceContext();

            context.QualifierValues["Language"] = "en-US";

            var resourceCandidate = manager.MainResourceMap.GetValue("Resources/String1/Text", context);
            var resourceString = resourceCandidate.ValueAsString;

            myButton.Content = resourceString;
        }
    }
}

画面側コード。

ボタンには、上のコードビハインドで、指定した言語(今回はen-US)のリソースを取ってきてセットするようにした。

その下のTextBlockには、自動で現在の言語設定に合わせたリソースがセットされるようにした。

<Window
    x:Class="LaungTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:LaungTest"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel Orientation="Vertical">
        <Button x:Name="myButton" />
        <TextBlock x:Uid="String1" Width="100" Height="100" TextAlignment="Center"/>
    </StackPanel>
</Window>

動かした結果

en-USのリソースを下記、

ja-JPにあるリソースを下記、

にして、

Windowsの現在の言語設定を日本語にしたときの動作が下記。

コードからとった方は「en」のほうのリソースになって、自動でセットされるほう(xamlで設定したほう)は、Windowsの言語設定の通り、jpになった。

参考

MS公式のリソース取得まわりサンプル
ここでも、今回やりたかったようなことがされてる。

https://github.com/microsoft/WindowsAppSDK-Samples/blob/1abe6431a40b38526fd8587f4166324b2e20c25a/Samples/ResourceManagement/cs-winui/winui_desktop_packaged_app/MainWindow.xaml.cs#L31

Using the Windows App SDK Resource Manager (MRT Core) in Unpackaged Win32 (WinForms/WPF) App.
この記事の真ん中より下あたりに、今回やりたかったことが書かれてる。

https://nicksnettravels.builttoroam.com/mrtcore-unpackaged/

ResourceContext.QualifierValues プロパティ

https://learn.microsoft.com/ja-jp/windows/windows-app-sdk/api/winrt/microsoft.windows.applicationmodel.resources.resourcecontext.qualifiervalues?view=windows-app-sdk-1.2

言語コードの表

https://learn.microsoft.com/en-us/windows/apps/publish/publish-your-app/supported-languages?pivots=store-installer-msix#supported-languages-1