Files
docs-desktop/dotnet-desktop-guide/framework/wpf/data/how-to-convert-bound-data.md
T
Andy (Steve) De George be103da07e Replace various WPF include files with content (#1335)
* net-current-v30plus-md.md

* net-current-v40plus-md.md

* tla2sharptla-ui-md.md

* tla2sharptla-uiautomation-md.md

* tla2sharptla-winclient-md.md

* tla2sharptla-xaml-md.md

* tlasharptla-ui-md.md

* tlasharptla-uiautomation-md.md

* tlasharptla-winclient-md.md

* tlasharptla-xaml-md.md

* fix warnings
2022-03-16 12:14:11 -04:00

2.4 KiB

title, ms.date, dev_langs, helpviewer_keywords, ms.assetid
title ms.date dev_langs helpviewer_keywords ms.assetid
How to: Convert Bound Data 03/30/2017
csharp
vb
converting [WPF], bound data
data binding [WPF], converting bound data
binding data [WPF], converting bound data
b00aaa19-c6df-4c3b-a9fd-88a0b488df2b

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 xref:System.Windows.Data.IValueConverter interface, which includes the xref:System.Windows.Data.IValueConverter.Convert%2A and xref:System.Windows.Data.IValueConverter.ConvertBack%2A 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 xref:System.Windows.Data.IValueConverter interface, it is a good practice to decorate the implementation with a xref:System.Windows.Data.ValueConversionAttribute attribute to indicate to development tools the data types involved in the conversion, as in the following example:

[!code-csharpDataBindingLab#18] [!code-vbDataBindingLab#18]

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.

[!code-xamlDataBindingLab#15]

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

[!code-xamlDataBindingLab#17]

The style resources referenced in the above example are defined in a resource section not shown in this topic.

See also