【问题标题】:How to load a specific language XAML file如何加载特定语言的 XAML 文件
【发布时间】:2020-11-16 22:54:05
【问题描述】:

我正在使用 XAML 文件构建我的语言系统。

我的代码如下:

es.xaml

<ResourceDictionary  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyAppTest"
    xmlns:system="clr-namespace:System;assembly=mscorlib">
    <system:String x:Key="Hello">Hola</system:String>
</ResourceDictionary>

en.xaml

<ResourceDictionary  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyAppTest"
    xmlns:system="clr-namespace:System;assembly=mscorlib">
    <system:String x:Key="Hello">Hello</system:String>
</ResourceDictionary>

App.xaml

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary x:Name="en" Source="mylang/en.xaml"/>
            <ResourceDictionary x:Name="es" Source="mylang/es.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Main.xaml

<TextBlock Text="{DynamicResource Hello}" />
<ComboBox>
   <ComboBoxItem Content="English" />
   <ComboBoxItem Content="Spanish" />
</ComboBox>

如何根据ComboBox中选择的语言读取语言XAML文件?

【问题讨论】:

  • 问:因此,您希望在程序执行时动态更改语言,以响应更改 ComboBox 中的选择。对吗?
  • @paulsm4 是的,就是这样
  • 这能回答你的问题吗? Change language at runtime in C# winform
  • @paulsm4 我相信不是因为这个链接使用 resx 文件而且我使用的是 xaml
  • Dude - 关键是您的 callback 需要修改 CurrentUICulture 属性,调用 ComponentResourceManager.ApplyResources 等。您的问题的答案涉及 C# 代码 i>,不仅仅是 XAML 标记!你的 ComboBox 有一个事件处理程序,不是吗?

标签: c# wpf xaml


【解决方案1】:

您可以通过使用DynamicResource 来实现您想要做的事情,就像您对TextBlock 所做的那样:

<TextBlock Text="{DynamicResource Hello}"/>

DynamicResource 标记扩展将在运行时重新加载资源,并在资源字典中添加、删除或替换它时更新它。您将为每种语言创建一个资源字典,并将它们放入应用程序资源字典中。

由于您不能将多个对象分配给资源字典中的同一个键,因此您的应用程序资源中应该只有当前应用语言的资源字典。通过交换当前语言资源字典,在代码中应用和切换语言。

为了设置初始语言,您可以加载您的语言设置并将相应的语言资源字典添加到App.xaml.cs 类中的应用程序资源中。使用 URI 并将其设置为资源字典的来源。我假设在这个示例中它是英文的。

var languageResourceDictionaryUri = new Uri("mylang/en.xaml");
var languageResourceDictionary = new ResourceDictionary { Source = languageResourceDictionaryUri };

Application.Current.Resources.MergedDictionaries.Add(languageResourceDictionary);

您应该存储对当前语言资源字典的引用,以便在用户使用 ComboBox 更改语言时将其从应用程序资源中删除。

Application.Current.Resources.MergedDictionaries.Remove(languageResourceDictionary);

然后,您将为所选语言添加一个新的资源字典,如上所述。根据您想要切换语言的位置,您可能需要创建一个服务来隐藏对更改资源所需的全局静态应用程序实例的访问。

【讨论】:

  • thatguy - 我认为这是正确的答案,但您没有因为谈论当前文化而混淆了这个问题吗?问题是关于如何在组合框更改时使用具有相同键的不同资源。 OP 根本没有提到文化或本地化。
  • @RichN。你是对的,这可能会混淆问题或者可能超出问题的范围,所以我删除了关于文化的评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-25
  • 1970-01-01
  • 2022-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多