共用方式為


HOW TO:轉換繫結的資料

這個範例顯示如何將轉換套用至繫結中使用的資料。

若要在繫結期間轉換資料,您必須建立實作 IValueConverter 介面的類別,這個介面包含 ConvertConvertBack 方法。

範例

下列範例顯示日期轉換器的實作,它會將傳入的資料值轉換,使其僅顯示年、月和日的資訊。 在實作 IValueConverter 介面時,在實作中加入 ValueConversionAttribute 屬性 (Attribute) 以向開發工具指出轉換時牽涉到的資料型別,是個不錯的做法,如下列範例所示:

[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;
    }
}

轉換器建立完成後,就可以將它加入您的Extensible Application Markup Language (XAML) 檔案中做為資源。 在下列範例中,src 對應至的命名空間是定義 DateConverter 的命名空間。

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

最後,您可以用下列語法在繫結中使用轉換器。 在下列範例中,TextBlock 的文字內容已繫結至外部資料來源的 StartDate 屬性 (Property)。

<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}"/>

上述範例中參考的樣式資源是在資源區段中定義,但是不會在這個主題中顯示。

請參閱

工作

HOW TO:實作繫結驗證

概念

資料繫結概觀

其他資源

資料繫結 HOW TO 主題