What is Value Converter in WPF ?

Converter are used in Data Binding. Converters are used when the source and target types are different, or when the target must have a different value than that of the source.

Converter is a class which implements ‘IValueConverter’.
The class must be decorated with the ‘[ValueConversion]’ attribute which lists the different data types used by the converter.
The IValueConverter interface consists of two methods : Convert() and ConvertBack().

  • Convert method gets when source is updating the target object.
  • ConvertBack method gets called when target is updating the source object.

Need of Value Converter

They are frequently used in Data Bindings
Like:

    • Suppose you have a checkbox and want it to change its value – checked on unchecked , based on a string value ‘yes’ or ‘no’
    • Or may be you have a numeric value and you want to display it other way like if the value is negative them the background color of Button should be red and if it is positive then it should be green

There are number of possibilities when we need to transform the value before it reaches destination.

Let us take an example-
You have a textbox and a checkbox. So based on the string value of Textbox, you want to color the checkbox to red if string = “fail” and green if it is “Pass”. And the textbox also should also reflect the changes when the checkbox is checked it should change its color to green and the Textbox value should become “pass” and if it is unchecked, the color should go to red and value of Textbox should also change to “Fail”.

ValueConverter

XAML

<Window x:Class=”ValueConverter.MainWindow”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:local=”clr-namespace:ValueConverter”
Title=”MainWindow” Height=”350″ Width=”525″><Window.Resources>
<local:ConvertClass x:Key=”studentConverter” />
</Window.Resources>
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width=”*” />
<ColumnDefinition Width=”*” />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height=”0.3*” />
<RowDefinition Height=”*” />
</Grid.RowDefinitions>
<TextBlock Text=”Performance Chart” Grid.ColumnSpan=”2″ Height=”40″ Width=”300″ Margin=”145,14,72,20″ FontSize=”25″ />
<TextBox x:Name=”txtstu” Width=”150″ Height=”40″ Grid.Row=”1″ Grid.Column=”0″ FontSize=”20″ />
<CheckBox FontSize=”20″ IsChecked=”{Binding ElementName=txtstu,Path=Text, Converter={StaticResource studentConverter}}”
Background=”{Binding Text, Converter={StaticResource studentConverter}, ElementName=txtstu}” Width=”100″ Height=”30″ Margin=”40″ Grid.Row=”1″ Grid.Column=”1″ Content=”Result” />
</Grid>

 

ConvertClass.cs file

namespace ValueConverter
{
public class ConvertClass : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string res = value.ToString().ToLower();
switch (res)
{
case “fail”:
return new SolidColorBrush(Colors.Red);
break;
case “pass”:
return new SolidColorBrush(Colors.LightGreen);
break;
default:
return new SolidColorBrush(Colors.Yellow);
}
}public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is bool)
{
if ((bool)value == true)
return “Pass”;
else
return “Fail”;
}
return “no”;
}
}




MultiValue Converter

It does the same work except that here the target is bound to multiple sources. Here We have to implement IMultiValueConverter.
And define two functions ‘Convert()’ and ‘ConvertBack()’

Suppose you have two Textboxes for ‘FirstName’ and ‘LastName’ and you want to bind both of these Textboxes with a third Textbox ‘Result’ such that the Result display the Full Name.

See the Figure and Code Below-
multivalueconverter

<Window x:Class=”ValueConverter.MultiConverter”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:local=”clr-namespace:ValueConverter”
Title=”MultiConverter” Height=”300″ Width=”450″>
<Window.Resources>
<local:MultiConvertClass x:Key=”multiconverter” />
</Window.Resources>
<Grid Margin=”20,20″ Background=”AliceBlue”>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=”*” >
<ColumnDefinition Width=”*” >
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height=”0.5*” >
<RowDefinition Height=”*” >
<RowDefinition Height=”*” >
<RowDefinition Height=”*” >
</Grid.RowDefinitions>
<TextBlock Text=”MultiValueConverter” Grid.ColumnSpan=”2″ Height=”40″ Width=”300″ FontSize=”25″ >
<TextBlock Text=”First Name” Grid.Row=”1″ Grid.Column=”0″ FontSize=”16″ HorizontalAlignment=”Center” VerticalAlignment=”Center” >
<TextBox x:Name=”txtFname” Width=”150″ Height=”30″ Grid.Row=”1″ Grid.Column=”1″ FontSize=”20″ >
<TextBlock Text=”Last Name” Grid.Row=”2″ Grid.Column=”0″ FontSize=”16″ HorizontalAlignment=”Center” VerticalAlignment=”Center”>
<TextBox x:Name=”txtLName” Width=”150″ Height=”30″ Grid.Row=”2″ Grid.Column=”2″ FontSize=”20″ >
<TextBlock Text=”Result” Grid.Row=”3″ Grid.Column=”0″ FontSize=”20″ HorizontalAlignment=”Center” VerticalAlignment=”Center” >
<TextBox x:Name=”txtRName” Width=”150″ Height=”30″ Grid.Row=”3″ Grid.Column=”2″ FontSize=”20″ >
<TextBox.Text>
<MultiBinding Converter=”{StaticResource multiconverter}”>
<Binding ElementName=”txtFname” Path=”Text” >
<Binding ElementName=”txtLName” Path=”Text” >
</MultiBinding>
</TextBox.Text>
</TextBox>
</Grid>
</Window>

.CS File

namespace ValueConverter
{
public class MultiConvertClass : IMultiValueConverter
{
public object Convert(object[] value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value[0] + ” ” + value[1];
}public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException(“Cannot convert back”);
}
}
}