【问题标题】:How can I display the current day of the week in XAML using the current regional settings?如何使用当前区域设置在 XAML 中显示当前星期几?
【发布时间】:2016-05-05 17:01:19
【问题描述】:

我有以下 XAML:

<Window x:Class="String_Format.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:s="clr-namespace:System;assembly=mscorlib"
        mc:Ignorable="d"
        Title="MainWindow" Height="150" Width="250">
    <StackPanel Margin="10">
        <TextBlock Name="TextBlock" Text="{Binding Source={x:Static s:DateTime.Now}, StringFormat=Date: {0:dddd, MMMM dd}}"/>
    </StackPanel>
</Window>

在 Visual Studio 2015 的 XAML 设计器以及正在运行的应用程序中,这显示为:“日期:1 月 28 日,星期四”。由于我使用的是德语 Windows 7,区域设置设置为“德语(德国)”,因此我实际上预期的是:“日期:Donnerstag,1 月 28 日”。

所以我去添加了命名空间

xmlns:c="clr-namespace:System.Globalization;assembly=mscorlib"

并将我的 TextBlock 更改为:

<TextBlock Name="TextBlock" Text="{Binding Source={x:Static s:DateTime.Now}, ConverterCulture={x:Static c:CultureInfo.CurrentCulture}, StringFormat=Date: {0:dddd, MMMM dd}}"/>

这确实会在运行时产生我想要的行为,但在 XAML 设计器中,它显示“无效标记”,并且没有显示我的窗口的预览。

有人问过before,但我想在 XAML 中完成,尽可能不使用代码。

那么我的 XAML 出了什么问题?我想了解。

【问题讨论】:

标签: c# wpf xaml globalization


【解决方案1】:

这确实会在运行时产生我想要的行为,但在 XAML 设计器中,它显示“无效标记”,并且没有显示我的窗口的预览。

这是因为添加的代码:ConverterCulture={x:Static c:CultureInfo.CurrentCulture} 在设计时无法解析。这会导致无效标记和缺乏显示。它在运行时解决,这就是您的日期以正确的语言/文化显示的原因。

您只能通过将其移动到可以检查它是运行时还是设计时的代码中来解决此问题。

【讨论】:

  • 为什么不能在设计时解决?我的意思是,s:DateTime.Now 可以解决,为什么c:CultureInfo.CurrentCulture 不能解决?有什么区别?
【解决方案2】:

检查是否在窗口上设置语言有帮助,我在窗口/用户控件等后面的代码中执行此操作:

this.Language = XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    相关资源
    最近更新 更多