WPF format DateTime in TextBlock?

前端 未结 3 803
再見小時候
再見小時候 2020-12-07 22:12

I have a TextBlock that is bound to a DateTime property. How do I configure the format of the date?

相关标签:
3条回答
  • 2020-12-07 22:24

    If you want to use a common format string between bindings, you could declare the binding like this:

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

    With your constants class like this:

    public static class Constants
    {
        public const string DateTimeUiFormat = "dd/MM/yyyy";
    
        //etc...
    }
    
    0 讨论(0)
  • 2020-12-07 22:29

    May be helpful to someone:

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

    or 24h and 2digits month and year format:

    <TextBlock Text="{Binding Source={x:Static sys:DateTime.Now},
               StringFormat='{}{0: Today is ffffdd, MM.dd.yy, HH:mm:ss}'}"/>
    
    0 讨论(0)
  • 2020-12-07 22:45

    There is a string format property available when you are declaring the binding:

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

    (You need to be on .NET 3.5 SP1 for this property to exist)

    0 讨论(0)
提交回复
热议问题