c# - 在 WPF 应用程序中单击按钮会重置文化

标签 c# wpf localization cultureinfo

我在 WPF 应用程序中看到了奇怪的行为(我确实在示例应用程序中复制了该行为)。

当应用程序启动时,我将 CultureInfo.CurrentCulture 和 CultureInfo.CurrentUICulture 设置为例如法语,在主应用程序窗口加载之前。然后主应用程序窗口加载并按预期显示本地化文本,法语,如下所示:

<Window.Resources>
  <Strings x:Key="Resources"/>
</Window.Resources

<Button Content={Binding Label, Source={StaticResource Resources}}/>

问题是,如果我单击该按钮,文化和按钮的文本将重置为 en-US。我为 Click 事件添加了一个事件处理程序,并在其中将 CurrentCulture 和 CurrentUICulture 都重置为“en-US”。

知道为什么会这样吗?这似乎很奇怪,这会以某种方式自动发生。

注意:我也试过

 var cultureName = CultureInfo.CurrentCulture.Name;
 FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement),
           new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(cultureName)));

this.Language = XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag);

在主窗口加载之前,区域性仍然会重置,但这无济于事。

更新:我也在 WPF 论坛 ( https://social.msdn.microsoft.com/Forums/vstudio/en-US/884af2cb-fcc3-4cfe-bea0-7a84f74583a8/culture-gets-reset-on-button-click?forum=wpf ) 上问过这个问题。在那里我描述了实际场景可能更好一些:我需要能够在应用程序启动时设置特定的文化,并在应用程序的整个生命周期中“保留”它。不幸的是,如前所述,单击按钮时文化会重置。

最佳答案

可能与您显示资源字符串的 Window.Resources->Binding 方法有关。我像这样显示本地化字符串:

<Window x:Class="CultureTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:p="clr-namespace:CultureTest.Properties"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Button Content="{x:Static p:Resources.Greeting}"/>
</Grid>

并在 App.OnStartup 中设置文化:

protected override void OnStartup(StartupEventArgs e)
{
    Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ru-RU");
    base.OnStartup(e);
}

它使它的文化保持良好。这是您的选择吗?

关于c# - 在 WPF 应用程序中单击按钮会重置文化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33304975/

相关文章:

.net - Silverlight 本地化错误?

c# - C#中的空指针异常

WPF 显示PasswordBox.Password

c# - 为 MVVM Light ICommand 正确使用 CanExecute

WPF 文本框包装

ios - Apple App Store 中应用所在的国家/地区

c# - 如何向用户报告标准异常?

c# - 在 C# 中使用 AES 加密

c# - 如何获取短名称格式的 Server.MapPath() (8.3 MS-DOS 格式)?

c# - return myVar 与 return (myVar) 之间有区别吗?