如何:轉換繫結的資料

此範例示範如何將轉換套用至系結中使用的資料。

若要在系結期間轉換資料,您必須建立實作 介面的 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

建立轉換器之後,即可將它新增為可延伸應用程式標記語言 (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}"/>

上述範例中所參考的樣式資源定義于本主題未顯示的資源區段中。

另請參閱