Share via


How to: Convert Bound Data

This example shows how to apply conversion to data that is used in bindings.

To convert data during binding, you must create a class that implements the IValueConverter interface, which includes the Convert and ConvertBack methods.

Example

The following example shows the implementation of a date converter that converts the date value passed in so that it only shows the year, the month, and the day. When implementing the IValueConverter interface, it is a good practice to decorate the implementation with a ValueConversionAttribute attribute to indicate to development tools the data types involved in the conversion, as in the following example:

[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.ToString();
        DateTime resultDateTime;
        if (DateTime.TryParse(strValue, out resultDateTime))
        {
            return resultDateTime;
        }
        return value;
    }
}

Once you have created a converter, you can add it as a resource in your Extensible Application Markup Language (XAML) file. In the following example, src maps to the namespace in which DateConverter is defined.

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

Finally, you can use the converter in your binding using the following syntax. In the following example, the text content of the TextBlock is bound to StartDate, which is a property of an external data source.

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

The style resources referenced in the above example are defined in the resource section of the sample not shown in this topic. For the complete code sample from which the above code examples were extracted, see Data Binding Demo.

See Also

Tasks

How to: Implement Binding Validation

Concepts

Data Binding Overview

Other Resources

Data Binding Samples
Data Binding How-to Topics