如何在 WPF 设计时显示多语言资源文本

How to display multilingual resource text at design time in WPF

我正在开发一个 WPF 应用程序,它应该是多语言的。 所以我按照 article 中的步骤向我的项目添加了一些资源字典。 然后我通过以下方法将这些词典之一添加到 window,出于测试目的,我正在 window:

的构造函数中调用该方法
    private void SetLanguageDictionary()
    {
        ResourceDictionary dict = new ResourceDictionary();

        switch (Thread.CurrentThread.CurrentCulture.ToString())
        {
            case "en-US":
            case "en-GB":
                dict.Source = new Uri("Resources\StringResources_en-US.xaml",
                              UriKind.Relative);
                break;
            case "de-DE":
                dict.Source = new Uri("Resources\StringResources_de-DE.xaml",
                                  UriKind.Relative);
                break;
            default:
                dict.Source = new Uri("Resources\StringResources_de-DE.xaml",
                                  UriKind.Relative);
                break;
        }

        Resources.MergedDictionaries.Add(dict);
    }

最后,我像这样在 window 的标签中实现了资源:

    <Label Grid.Row="0"
           Grid.Column="0"
           Margin="5"
           Content="{DynamicResource firstname}"></Label>

如果我 PC 上的当前文化是 "en-US",则内容将是 "First name"。 或者 "de-DE"(德语)"Vorname".

在运行时它工作正常,但在设计时我看不到文本。

我该怎么办?

我找到了。

我必须在 Window.Resources 中实现 ResourceDictionary。 为此,必须添加一些标签 ("ResourceDictionary"、"ResourceDictionary.MergedDictionaries")。

如果定义了样式,则必须将它们移动到标签内 "ResourceDictionary",如下所示。

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Resources/StringResources_en-US.xaml"/>
        </ResourceDictionary.MergedDictionaries>

        <Style x:Key="style1">
            [...]
        </Style>

        [...]
    </ResourceDictionary>
</Window.Resources>

然后您可以在作为动态资源绑定到它的控件中看到来自 xaml-file 的文本。 又因为是作为动态资源使用,所以可以在code-behind:

中覆盖
        ResourceDictionary dict = new ResourceDictionary();
        dict.Source = new Uri("Resources\StringResources_de-DE.xaml",
                                  UriKind.Relative);
        Resources.MergedDictionaries.Add(dict);