我在 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/