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 cod
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.Now
is 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 StaticSurrogate
class, where I would create instance properties for the static properties that we need access to:-
public class StaticSurrogate
{
public DateTime Today { get { return DateTime.Today; } }
public DateTime Now { get { return DateTime.Now; } }
}
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 :-
public class FormatConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (parameter != null)
{
string formatterString = parameter.ToString();
if (!String.IsNullOrEmpty(formatterString))
{
return String.Format(culture, String.Format("{{0:{0}}}", formatterString), value);
}
}
return (value ?? "").ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
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:-
StaticSurrogate
class.