Jul 9, 2011

Using StringFormat for Binding in Silverlight: Viral Rathod

Dear Friends,

While, doing an optimization of our product, with my colleague RamKrishn Saini, we found some interesting stuff for Rapid coding and Performance in Silverlight 4.0 Application.

While Binding the DataGrid, inside a Text Column, we have previously used Converters, to Create our Require Date format inside our application. Which had consumed Time for coding and Performance of application as well.

i.e.,

XAML CODE:

<TextBlock Text="{Binding ENTRY_DATE,Converter={StaticResource ConvertFormatDateTime}}" / >

Code behind for Converter:

public class ConvertFormatDateTime : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
if (value.ToString().Contains("1/1/0001") || value.ToString().Contains("1900"))
return "-";
else
return System.Convert.ToDateTime(value).ToString();//("dd MMM yyyy hh:mm:ss");
}
else
return "";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}


Output: 05 Jul 2011 5:37:22

Now,
Using String Format it very Easy to code which is as follows:


i.e.,

XAML CODE:

<TextBlock Text="{Binding Path= ENTRY_DATE,StringFormat=f}" />

Output: Tuesday, July 05, 2011 5:37 PM

==================================================
CONCLUSION
==================================================

No need to code more, just in Single line reflection, Following are some other formats for Date Time:

StringFormat=f : “Saturday, April 17, 2004 1:52 PM”
StringFormat=g : “4/17/2004 1:52 PM”
StringFormat=m : “April 17”
StringFormat=y : “April, 2004”
StringFormat=t : “1:52 PM”
StringFormat=u : “2004-04-17 13:52:45Z”
StringFormat=o : “2004-04-17T13:52:45.0000000”
StringFormat=’MM/dd/yy’ : “04/17/04”
StringFormat=’MMMM dd, yyyy g’ : “April 17, 2004 A.D.”
StringFormat=’hh:mm:ss.fff tt’ : “01:52:45.000 PM”


MDSN article for standard date formatting

MSDN article for custom date formatting

Thanks, for Reading this post. I will bring some more live scenario interesting facts soon.