What are Converters in WPF?

Open 1 Answers 12 Views Education

1 Answer

Converters provide substantial supremacy since they allow insertion of an object between a source and a target object. At a high level, converters are a chunk of custom code hooked up using the binding and the data will flow via that converter. So, whenever data is flown from a source to a target, one can change the value or can change the type of object that needs to be set on the target property.
So, whenever data travels from source to target, it can be transformed in two ways:
  1. Data value: Here the transformation will be done with just the value by keeping the data type intact. For example, for number fields, you can transform a value from a floating point number to an integer by keeping the actual value as a float.
  2. Data type: One can also transform the data type. For example, setting a style based on some Boolean flag.
Defining a converter
Defining any converter requires implementation of an IValueConverter interface in a class. This interface has the following two methods:
  1. Convert: Is called when data is flowing from a source to a target.
  2. ConvertBack: Is called when data is flowing from a target to a source. It is basically useful in two-way binding scenarios.
How to use
Once your class is part of a ResourceDictionary, you can point to the instance of the converter using the Converter property of Binding, along with a StaticResource markup extension.
Where to place converters
To implement an IValueConverter one must create a class and then put the instance of that class in a ResourceDictionary within your UI.
by (302k points)