【问题标题】:WPF application use the wrong language for formatting DateTimeWPF 应用程序使用错误的语言格式化 DateTime
【发布时间】:2015-12-18 16:53:25
【问题描述】:

我正在使用 Visual Studio 2015 开发 WPF 应用程序,以法语安装,但我使用的是英语语言包。我有一个法语 Windows 10,一个法语键盘布局,Windows 区域是加拿大。在我的应用程序中,我使用 Application_Startup 中的以下代码明确地将文化设置为“en-CA”:

var culture = CultureInfo.GetCultureInfo("en-CA");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;

FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement),
            new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

然后,在回答 SO 之后,在我的主窗口的构造函数中:

this.Language = XmlLanguage.GetLanguage("en-CA");

在列表视图中,我使用它的 DisplayString 属性显示一个对象,即:

return Start.ToString("dd MMM") // Start is a DateTime

列表视图定义为

<ListView x:Name="lvEntries" Margin="435,81,10,5" SelectionChanged="lvEntries_SelectionChanged" 
      SelectionMode="Single" MaxHeight="516" HorizontalAlignment="Left" Height="412" VerticalAlignment="Top" FontFamily="Consolas" >
<ListView.View>
    <GridView AllowsColumnReorder="False">
        <GridViewColumn Header="Period" DisplayMemberBinding="{Binding DisplayString}" />
        <GridViewColumn Header="Project" DisplayMemberBinding="{Binding ProjectName}" />
    </GridView>
</ListView.View></ListView>

应用程序启动时一切正常,但单击任何按钮后,日期时间的格式使用月份的法语缩写。 例如:之前:“12 月 14 日”,“14 月 14 日”之后。

导致问题的按钮单击示例:

private void btnSave_Click(object sender, RoutedEventArgs e)
{
    String s = DateTime.Now.ToString("dd MMM"); // this returns the french abbreviation
    Save();
}

我没有任何线程正在运行,也没有涉及其他地方文化的代码。我正在使用最新的实体框架来处理我的数据。

我可以根据需要显示更多代码,但我想不出其他任何相关的内容。

【问题讨论】:

  • 您使用的是 .NET 4.5 或更高版本吗?如果是这样,请尝试设置 CultureInfo.DefaultThreadCurrentCultureCultureInfo.DefaultThreadCurrentUiCultureMSDN documentation 解释了这些新属性。
  • @Vache 已解决,谢谢。将其发布为答案?

标签: c# .net wpf culture


【解决方案1】:

即使您没有显式创建新线程,框架也可能在调用您的事件处理程序之前完成它。

如果您使用的是 .NET 4.5 或更新版本,请尝试设置 CultureInfo.DefaultThreadCurrentCultureCultureInfo.DefaultThreadCurrentUiCulture

MSDN documentation 解释了这些新属性,但它们的名称不言自明。

如果未设置这些属性,则新线程的文化默认为操作系统的文化。 Culture and threads 也是一本有趣的书。

【讨论】:

    猜你喜欢
    • 2012-07-04
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多