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
No comments:
Post a Comment