Friday, April 29, 2011

date converter for displaying a short date string from a date object

We (WPF/Silverlight developers) typically use date converter in almost every WPF or Silverlight app. Below is the code for converting date time object to a short date string.

C# code:


[ValueConversion(typeof(DateTime), typeof(String))]
    public class DateConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DateTime date = (DateTime)value;
            return date.ToShortDateString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string strValue = value as string;
            DateTime resultDateTime;
            if (DateTime.TryParse(strValue, out resultDateTime))
            {
                return resultDateTime;
            }
            return DependencyProperty.UnsetValue;
        }
    }

VB.net code:

<ValueConversion(GetType(DateTime), GetType([String]))> _
Public Class DateConverter
Implements IValueConverter
Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object
Dim [date] As DateTime = DirectCast(value, DateTime)
Return [date].ToShortDateString()
End Function

Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object
Dim strValue As String = TryCast(value, String)
Dim resultDateTime As DateTime
If DateTime.TryParse(strValue, resultDateTime) Then
Return resultDateTime
End If
Return DependencyProperty.UnsetValue
End Function
End Class

XAML code for displaying "Star" shape

 <Polygon  Fill="Yellow" Stroke="Black" StrokeThickness=".5" StrokeLineJoin="Round" Width="15" Height="15" Stretch="Fill" Points="10,2 10,7 17,7 12,10 14,15 9,12 4,15 6,10 1,7 7,7" Name="star"/>