【问题标题】:How to display multilingual resource text at design time in WPF如何在 WPF 中的设计时显示多语言资源文本
【发布时间】:2023-07-28 07:49:01
【问题描述】:

我正在开发一个多语言的 WPF 应用程序。 所以我按照article 中的步骤,在我的项目中添加了一些资源字典。 然后我通过以下方法将这些字典之一添加到窗口中,我在窗口的构造函数中调用 - 用于测试目的:

    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);
    }

最后我在我的窗口的标签中实现了这样的资源:

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

如果我电脑上的当前文化是“en-US”,则内容将是“名字”。 或者在“de-DE”(德语)“Vorname”的情况下。

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

我该怎么办?

【问题讨论】:

  • 我认为您可能会这样做,我使用 Content="{Binding CommonDate, Source={StaticResource Resources}}" 其中 Resources 是 Resources.resx
  • 这听起来像是依赖注入的工作。我使用来自 NuGet 的 MVVM Light 工具包 - 默认情况下,您绑定的数据将来自两个数据服务(存储库)之一 - 您有一个设计数据服务,它处理用于设计的虚拟数据,以及您的生产数据服务,用于运行。在您的视图模型中,您从数据服务中检索要绑定到的对象,但您将获得不同的对象,具体取决于正在使用的数据服务(这又取决于您是否处于设计模式。)您可以在以下位置找到更多信息mvvmlight.codeplex.com

标签: c# wpf xaml resourcedictionary


【解决方案1】:

我已经找到了。

我必须在 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 文件的文本。 并且因为它被用作动态资源,它可以在代码隐藏中被覆盖:

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

【讨论】:

    最近更新 更多