WPF Binding StringFormat Short Date String

I would like to use Short Date named string format in WPF.

I tried something like:

<TextBlock Text="{Binding Date, StringFormat='Short Date'}" /> 

How to do it?

+83
wpf binding xaml
Feb 18 '11 at 20:50
source share
5 answers

Try the following:

 <TextBlock Text="{Binding PropertyPath, StringFormat=d}" /> 

which is culture sensitive and requires .NET 3.5 SP1 or higher.

NOTE. It is case sensitive. "d" is a short date format specifier , and "D" is a long date format specifier .

There is a complete list of string formats on this MSDN blog post page.

However, there is one question with this - it always displays the date in US format, if you yourself do not set the culture to the correct value.

If you do not set this property, the binding mechanism uses the Language property of the binding target. In XAML, this defaults to "en-US" or inherits the value from the root element (or any element) of the page, if it is explicitly set.

Source

One way to do this in the code behind (assuming you have configured the thread culture to the correct value):

 this.Language = XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name); 

Another way is to set the converter culture in binding:

 <TextBlock Text="{Binding PropertyPath, StringFormat=d, ConverterCulture=en-GB}" /> 

Although this does not allow you to localize the output.

+162
Feb 18 2018-11-18T00:
source share

Or use this for English (or mix it for custom) format:

 StringFormat='{}{0:dd/MM/yyyy}' 
+44
04 Sep
source share

Use the StringFormat property (or ContentStringFormat on ContentControl and its derivatives, such as Label ).

 <TextBlock Text="{Binding Date, StringFormat={}{0:d}}" /> 

Pay attention to {} before the standard notation of the positional argument String.Format allows String.Format to copy braces in the markup extension language.

+23
Feb 18 2018-11-18T00:
source share

Just use:

 <TextBlock Text="{Binding Date, StringFormat=\{0:d\}}" /> 
+4
Feb 18 '11 at 20:53
source share

If you want to add a string with a value, use this:

 <TextBlock Text="{Binding Date, StringFormat= 'Date : {0:d}'}" /> 
+3
Apr 02 '17 at 7:27
source share



All Articles