TextBlock中的WPF格式DateTime?

Pet*_*ter 60 wpf formatting textblock

我有一个TextBlockDateTime财产绑定的.如何配置日期格式?

Mar*_*ris 122

声明绑定时,可以使用字符串格式属性:

<TextBox Text="{Binding Path=DateTimeValue, StringFormat=dd-MM-yyyy}" />
Run Code Online (Sandbox Code Playgroud)

(您需要在.NET 3.5 SP1上才能存在此属性)

  • 只是让你知道这是TextBox < - 资本B (3认同)

Bri*_*hey 30

如果要在绑定之间使用通用格式字符串,可以像这样声明绑定:

<Textbox Text={Binding Path=DateTimeValue, StringFormat={x:Static local:Constants.DateTimeUiFormat}} />
Run Code Online (Sandbox Code Playgroud)

使用这样的常量类:

public static class Constants
{
    public const string DateTimeUiFormat = "dd/MM/yyyy";

    //etc...
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢布莱恩!我将它与 System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.ShortDatePattern 结合使用以获得 i18n 短日期。 (2认同)

小智 19

可能对某人有帮助:

<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now},
           StringFormat='{}{0: Today is dddd, MMMM dd, yyyy, hh:mm:ss}'}"/>
Run Code Online (Sandbox Code Playgroud)

或24小时和2小时的月份和年份格式:

<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now},
           StringFormat='{}{0: Today is dddd, MM.dd.yy, HH:mm:ss}'}"/>
Run Code Online (Sandbox Code Playgroud)