Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom DateTime stringformat in WPF

I can't get my custom DateTime string format to work in my binding. I want the format to be "mmmm, yyyy" (e.g. "June, 2012").

The following does not work. I get a short date format (m/d/yyyy).

<TextBlock Text="{Binding ElementName=ThisWindow,
                          Path=Date,
                          StringFormat={}{0:MMMM\, yyyy}"/>

I've considered using a converter, but I prefer a pure XAML approach.

Edit:

For clarity, I have a Window with a dependency property Date of type DateTime. In my XAML, I've named the window 'Thiswindow'.

Edit 2:

I looked back at my actual code, and I had a Label, not a TextBlock. I changed it to TextBlock and it works fine.

<Label Content="{Binding ElementName=ThisWindow,
                 Path=Date,
                 StringFormat={}{0:MMMM\, yyyy}"/>

Anyone know why it doesn't work with Label?

Thanks.

like image 283
gregsdennis Avatar asked Jun 08 '12 16:06

gregsdennis


2 Answers

ContentControls have a ContentStringFormat property which overrides the original formatting.

(When i saw your question i expected this to be the problem actually but was surprised to find a TextBlock at first)

like image 192
H.B. Avatar answered Sep 28 '22 02:09

H.B.


Your month needs to be in uppercase:

{Binding Source={x:Static sys:DateTime.Now}, StringFormat={}{0:MMMM\, yyyy}}

EDIT:

The Label problem is probably because Label has Content, not Text.

Change the Text="{Binding ...}" to Content="{Binding ...}"

like image 30
Trevor Elliott Avatar answered Sep 28 '22 02:09

Trevor Elliott