WPF格式DateTime在TextBlock中?


Answers:


140

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

<TextBox Text="{Binding Path=DateTimeValue, StringFormat=dd-MM-yyyy}" />

(您必须在.NET 3.5 SP1上才能存在此属性)


3
只是让您知道这就是TextBox <-首
Alex

35

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

<Textbox Text={Binding Path=DateTimeValue, StringFormat={x:Static local:Constants.DateTimeUiFormat}} />

使用这样的常量类:

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

    //etc...
}

1
谢谢布莱恩!我将此与结合使用System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.ShortDatePattern以获得i18n短日期。

23

可能对某人有帮助:

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

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

<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now},
           StringFormat='{}{0: Today is dddd, MM.dd.yy, HH:mm:ss}'}"/>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.