This one is easy on the brain. Some quick WPF lovin’ 101.
I need to display the current date, and have it formatted like this:
Friday, March 13, 2009
In my opinion, this is purely a matter for the view and so I’m handling it entirely in the xaml. Here’s the markup:
<TextBlock Text="{Binding Source={x:Static sys:DateTime.Today},
StringFormat='{}{0:dddd, MMMM dd, yyyy}'}"/>
And now for a quick analysis.
I wanted to use the builtin DateTime structure, because there is no need for me to expose the current time through my presentation/view model. In my root element, I create a namespace alias:
xmlns:sys="clr-namespace:System;assembly=mscorlib"
This allows me to reference DateTime in the markup. Since DateTime has a static property, I can get at it using StaticExtension. So far, that explains {x:Static sys:DateTime.Today}. I’m working from the inside out.
Inside the binding, I need to set the Source property because otherwise the binding is looking to the DataContext. We don’t care about the context, we just want to directly access the value of DateTime.Today.
Finally, we have StringFormat. It’s a tasty little bit that was introduced in 3.5sp1. You can pass it any of your standard formatting strings and it just works. Let’s say that I want to display this:
Today is Friday March 13.
I could used:
<TextBlock Text="{Binding Source={x:Static sys:DateTime.Today},
StringFormat=Today is {0:dddd, MMMM dd}}"/>
Notice that my quotes from the first example were omitted. They are actually optional. I like to include them though for readability.
You might also have notice in the first example an extra set of angle brackets. If your formatting string starts off with an angle bracket, the Xaml parser gets confused. It thinks that it’s encountering another markup extension. We have to use an escape sequence and in Xaml it’s {}.
Once final note, DateTime doesn’t raise any change notification. So don’t expect the view to be update as the time changes.
Posted
03-13-2009 6:06 PM
by
Christopher Bennage