如何:转换绑定的数据

此示例演示如何将转换应用于绑定中使用的数据。

若要在绑定期间转换数据,必须创建一个实现 IValueConverter 接口的类,此操作涉及使用到 ConvertConvertBack 方法。

示例

以下示例演示日期转换器的实现,该转换器转换传入的日期值,以便仅显示年份、月份和日期。 实现 IValueConverter 接口时,一个好的做法是使用 ValueConversionAttribute 属性来修饰实现,以便向开发工具指示转换中涉及的数据类型,如下例所示:

[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;
    }
}
Public Class DateConverter
    Implements System.Windows.Data.IValueConverter

    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 DateValue As DateTime = CType(value, DateTime)
        Return DateValue.ToShortDateString

    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 strValue As String = value
        Dim resultDateTime As DateTime
        If DateTime.TryParse(strValue, resultDateTime) Then
            Return resultDateTime
        End If
        Return DependencyProperty.UnsetValue

    End Function
End Class

创建转换器后,可以在 Extensible Application Markup Language (XAML) 文件中将其添加为资源。 在以下示例中,src 映射到定义 DateConverter 的命名空间

<src:DateConverter x:Key="dateConverter"/>

最后,可以使用以下语法在绑定中使用转换器。 在以下示例中,TextBlock 的文本内容绑定到 StartDate,它是外部数据源的属性

<TextBlock Grid.Row="2" Grid.Column="0" Margin="0,0,8,0"
           Name="startDateTitle"
           Style="{StaticResource smallTitleStyle}">Start Date:</TextBlock>
<TextBlock Name="StartDateDTKey" Grid.Row="2" Grid.Column="1" 
    Text="{Binding Path=StartDate, Converter={StaticResource dateConverter}}" 
    Style="{StaticResource textStyleTextBlock}"/>

以上示例中引用的样式资源在本主题中未展示的资源节中定义。

另请参阅