这允许您配置日期时间格式。
VB代码
Imports System.Windows.Data
Public Class DateTimeToString
Implements IValueConverter
Private _Format As String
Public Property Format() As String
Get
Return _Format
End Get
Set(ByVal value As String)
End Set
End Property
Public Function Convert(ByVal value As Object, _
ByVal targetType As System.Type, _
ByVal parameter As Object, _
ByVal culture As System.Globalization.CultureInfo) As Object _
Implements System.Windows.Data.IValueConverter.Convert
Dim DateTimeValue As DateTime
If DateTime.TryParse(value, DateTimeValue) Then
Return DateTimeValue.ToString(_Format)
End If
Return value
End Function
Public Function ConvertBack(ByVal value As Object, _
ByVal targetType As System.Type, _
ByVal parameter As Object, _
ByVal culture As System.Globalization.CultureInfo) As Object _
Implements System.Windows.Data.IValueConverter.ConvertBack
Dim StringValue As String = value.ToString
Dim DateTimeValue As DateTime
If DateTime.TryParse(StringValue, DateTimeValue) Then
Return DateTimeValue
End If
Return value
End Function
End Class
C# 代码
public class DateTimeToString : IValueConverter
{
public string Format { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
DateTime DateTimeValue = (DateTime)value;
return DateTimeValue.ToString(Format);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
string strValue = value.ToString();
DateTime DateTimeValue;
if (DateTime.TryParse(strValue, out DateTimeValue))
return DateTimeValue;
return value;
}
}
XAML 代码
<TextBlock Text="{Binding BirthDate, Converter={StaticResource DateToString}}" />