Click here to Skip to main content
15,911,707 members
Articles / Desktop Programming / WPF
Tip/Trick

IValueConverter Example and Usage in WPF

Rate me:
Please Sign up or sign in to vote.
3.70/5 (8 votes)
21 Jan 2015CPOL1 min read 92.2K   1.2K   12   8
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Dover India pvt ltd
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionArticle copy Pin
Bernhard Hiller31-Jul-17 21:04
Bernhard Hiller31-Jul-17 21:04 
Suggestioncombobox with IsChecked? Pin
Huh? Come Again?27-Jan-15 21:30
Huh? Come Again?27-Jan-15 21:30 
GeneralRe: combobox with IsChecked? Pin
Nomesh G16-Feb-15 21:26
Nomesh G16-Feb-15 21:26 
GeneralMy vote of 4 Pin
MahBulgariaReborn22-Jan-15 2:10
MahBulgariaReborn22-Jan-15 2:10 
GeneralRe: My vote of 4 Pin
Nomesh G22-Jan-15 2:32
Nomesh G22-Jan-15 2:32 
GeneralRe: My vote of 4 Pin
MahBulgariaReborn22-Jan-15 2:49
MahBulgariaReborn22-Jan-15 2:49 
GeneralImages not visible Pin
Klaus Luedenscheidt21-Jan-15 19:09
Klaus Luedenscheidt21-Jan-15 19:09 
GeneralRe: Images not visible Pin
Nomesh G26-Jan-15 18:48
Nomesh G26-Jan-15 18:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.