Binding is one of the big features in WPF which helps us to facilitate data flow between WPF UI and Object. But when data flows from source to UI or vice-versa using these bindings we need to convert data from one format to other format. For instance let’s say we have a “Person” object with a married string property.
Let’s assume that this “married” property is binded with a check box. So if the text is “Married” it should return true so that the option check box look’s checked. If the text is “Unmarried” it should return false so that the option check box looks unchecked.
In simple words we need to do data transformation. This is possible by using “Value Converters”. In order to implement value converters we need to inherit from “IValueConverted” interface and implement two methods “Convert” and “ConvertBack”.
public class MaritalConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string married = (string)value; if (married == "Married") { return true; } else { return false; } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool married = (bool)value; if (married) { return "Married"; } else { return "UnMarried"; } } }
You can see in the “Convert” function we have written logic to transform “Married” to true and from “Unmarried” to false. In the “Convertback” function we have implemented the reverse logic.