I am coming from Flex where you can do just about anything inside of curly braces. I am trying to get a TextBlock to display today’s Date and Time without just coding it in C#. I have tried many different variations of the following with no luck.
TextBlock Text="{Source=Date, Path=Now, StringFormat='dd/MM/yyyy'}"
I know I could probably just set a property MyDate and bind to that but why can’t I bind directly to the DateTime.Now property?
Binding in Silverlight requires a Source object or a Dependency object. From that source object you can bind to Properties (hence by definition you are binding to instance members) or Dependency Properties.
Since
DateTime.Nowis a static property you cannot bind to it in Silverlight directly, hence some code is needed. The next best thing is to use code to:-Hence we can analyse that we need two things.
To handle the first item I would create a
StaticSurrogateclass, where I would create instance properties for the static properties that we need access to:-Now we need a way to format a Date time. A value converter is the right tool for this job, borrowing heavily from this Tim Heuer Blog :-
With these two classes in place we can now do the rest in Xaml, first we need instances of these classes in our resources:-
Now we can wire up the
TextBlock:-Note that this approach has the following advantages:-
StaticSurrogateclass.