WPF format DateTime in TextBlock?

WpfFormattingTextblock

Wpf Problem Overview


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

Wpf Solutions


Solution 1 - Wpf

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)

Solution 2 - Wpf

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

Solution 3 - Wpf

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}'}"/>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeterView Question on Stackoverflow
Solution 1 - WpfMartin HarrisView Answer on Stackoverflow
Solution 2 - WpfBrian HincheyView Answer on Stackoverflow
Solution 3 - WpfZloyMakakView Answer on Stackoverflow