Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

IValueConverter Example and Usage in WPF

0.00/5 (No votes)
21 Jan 2015 1  
Implementation and usuage of ValueConverter.

Introduction

Value converters are used in Data binding. When source object type and target object type are different at that time value converts are used to manipulate data between source and target. Converter class must implement IValueConverter interface. The IValueConverter interface consists of two methods, Convert() and ConvertBack().

Convert method gets called when source updates target object.

ConvertBack method gets called when target updates source object.

Background

Let’s look at this with a simple example.

Our final application will look like this:

So basically, we are binding string value from textbox to Ischecked property of the combobox. But IsChecked requires a Boolean value. So here is where the Value converter concept kicks in where we convert text value from textbox to boolean value to set IsChecked property.

Using the Code

So let's start building our application.

We add a WPF project and modify the MainWindow.xaml as follows:

XML
<Window x:Class="IValueConverterExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="IValueConverterExample" Height="100" Width="300"
        xmlns:local="clr-namespace:IValueConverterExample">

    <Window.Resources>
        <local:YesNoToBooleanConverter x:Key="YesNoToBooleanConverter"/>
    </Window.Resources>

    <Grid>
        <StackPanel Margin="10">
            <TextBox Name="txtValue" />

            <CheckBox IsChecked="{Binding ElementName=txtValue, 
                                          Path=Text, 
                                          Converter={StaticResource YesNoToBooleanConverter}}" 
                      Content="Yes" />
        </StackPanel>
    </Grid>
</Window>

Implementing IValueConverter

We will add a new class called YesNoToBooleanConverter that implements IValueConverter interface.

C#
public class YesNoToBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, 
                System.Globalization.CultureInfo culture)
        {
            switch (value.ToString().ToLower())
            {
                case "yes":
                    return true;
                case "no":
                    return false;

                default:
                    return Binding.DoNothing;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, 
                System.Globalization.CultureInfo culture)
        {
            if (value is bool)
            {
                if ((bool)value == true)
                    return "yes";
                else
                    return "no";
            }
            return "no";
        }
    }

The Convert() methods assume that it receives a string as the input (the value parameter) and then converts it to a Boolean true or false value. The Binding.DoNoting as the name suggests does not change the target, but leaves the target with the same state as it is before.

The ConvertBack() method obviously does the opposite: It assumes an input value with a Boolean type and then returns the English word "yes" or "no" in return, with a fallback value of "no".

I hope this helps you out in using the IValueConverter.

Points of Interest

There are various inbuilt valueconverters that may come in handy. Here are the examples:

C#
System.Windows.Controls.AlternationConverter
System.Windows.Controls.BooleanToVisibilityConverter
System.Windows.Documents.ZoomPercentageConverter
System.Windows.Navigation.JournalEntryListConverter

Xceed.Wpf.DataGrid.Converters.CurrencyConverter
Xceed.Wpf.DataGrid.Converters.DateTimeToStringConverter
Xceed.Wpf.DataGrid.Converters.GreaterThanZeroConverter
Xceed.Wpf.DataGrid.Converters.IndexToOddConverter
Xceed.Wpf.DataGrid.Converters.IntAdditionConverter
Xceed.Wpf.DataGrid.Converters.InverseBooleanConverter
Xceed.Wpf.DataGrid.Converters.LevelToOpacityConverter
Xceed.Wpf.DataGrid.Converters.MultimodalResultConverter
Xceed.Wpf.DataGrid.Converters.NegativeDoubleConverter
Xceed.Wpf.DataGrid.Converters.NullToBooleanConverter
Xceed.Wpf.DataGrid.Converters.SourceDataConverter
Xceed.Wpf.DataGrid.Converters.StringFormatConverter
Xceed.Wpf.DataGrid.Converters.ThicknessConverter
Xceed.Wpf.DataGrid.Converters.TypeToBooleanConverter
Xceed.Wpf.DataGrid.Converters.TypeToVisibilityConverter
Xceed.Wpf.DataGrid.Converters.ValueToMaskedTextConverter

Thanks for reading this tip. Any improvements on this will be appreciated.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here