Using value converters
Converters are often useful when you want to perform data binding between two properties that have incompatible types. In such cases, you will need a piece of code which creates a bridge between source and target. This piece of code is defined as a value converter.
The IValueConverter
interface is used to create value converters and contains two methods named Convert
and ConvertBack:
- Convert(...): It gets called when the source updates the target object
- ConvertBack(...): It gets called when the target object updates the source object
In this recipe, we will learn how to create value converters and use them while data binding.
Getting ready
Let's begin by creating a new WPF project. Call it CH04.ConverterDemo
.
How to do it...
To begin with the value converter, perform the following steps:
- From the
Solution Explorer
, open theMainWindow.xaml
file. - Replace the existing
Grid
with the following XAML markup, which contains aCheckBox
and aRectangle
inside aStackPanel
:
<StackPanel...