Peter
Peter

Reputation: 38465

WPF format DateTime in TextBlock?

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

Upvotes: 82

Views: 122337

Answers (4)

AXin
AXin

Reputation: 21

<TextBlock Text="{Binding Path=DateTimeValue, StringFormat='Today is {0: dd/MM/yyyy}'}" />

Upvotes: 0

Martin Harris
Martin Harris

Reputation: 28617

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)

Upvotes: 157

ZloyMakak
ZloyMakak

Reputation: 429

May be helpful to someone:

<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now},
           StringFormat='{}{0: Today is dddd, 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 dddd, MM.dd.yy, HH:mm:ss}'}"/>

Upvotes: 30

Brian Hinchey
Brian Hinchey

Reputation: 3691

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...
}

Upvotes: 39

Related Questions