WPF Value Converters

Kailash Chandra Behera | Monday, July 04, 2016

Introduction

In my previous article i have briefly about converters and the type of converters. Now in this article we will discuss deeply one of the converter that is value converter.

Getting Started

A Value Converter act as a bridge between a target and a source while data flowing and it is necessary when the datatype of source and target are different for instance you have a text box and a button control. You want to enable or disable the button control when the text of the text box is filled or null.

To set the text of textbox text property is required and the datatype of text property of textbox is a string and to set enable or disable button IsEnable property of the button is required and the datatype of IsEnable is boolean.

In this case, you need to convert the string data to Boolean. This is possible using a Value Converter. To implement Value Converters, there is the requirement to inherit from IValueConverter in the System.Windows.Data namespace and implement the two methods Convert and ConvertBack. Let's illustrates the Value Converter with code example, below code demonstrate how to use Value Converter in WPF. This below code creates a Value Converter by implementing IValueConverter interface.

 using System;    
  using System.Collections.Generic;    
  using System.Linq;    
  using System.Text;    
  using System.Threading.Tasks;    
  using System.Windows.Data;    
  namespace ValueConverters    
  {    
   public class ValueConverter:IValueConverter    
   {    
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)    
    {    
     bool isenable = true;    
     if (string.IsNullOrEmpty(value.ToString()))    
     {    
      isenable = false;    
     }    
     return isenable;    
    }    
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)    
    {    
     throw new NotImplementedException();    
    }    
   }    
  }    

In the preceding code I have created a class named Value Converter that will convert the value from the source to the target. This class does the conversion of the WPF value by implementing IValueConverter. There are two methods in the Value Converter class that are implemented from the IValue Converter interface. The Convert method helps to do the conversion from the target to the source and ConvertBack converts from the Source to the Target.

Here in the preceding code I have written code in the convert method to enable or disable the button control and have not written any code in the ConvertBack function. To use the convert back I have another example.

Let's say you have a check box control bound the text with the text of text box control. You want to determine whether the check box is checked when the text is married and unchecked when the text is unmarried.

 using System;    
  using System.Collections.Generic;    
  using System.Linq;    
  using System.Text;    
  using System.Threading.Tasks;    
  using System.Windows.Data;    
  namespace ValueConverters    
  {    
   class CheckBoxCheckConverter:IValueConverter    
   {    
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)    
    {    
     if (value.ToString().ToUpper() == "MARRIED")    
     {    
      return true;    
     }    
     else    
     {    
      return false;    
     }    
    }    
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)    
    {    
     bool married = System.Convert.ToBoolean(value);    
     if (married == true)    
      return "Married";    
     else    
      return "Unmarried";    
    }    
   }    
  }    

In the preceding code, I am checking the text of text box. If it is married then the convert function returns true that will make the check box checked otherwise it will uncheck the checkbox. The convert back function is doing as said above, if the check box is checked it is setting the text of the TextBox to Married and otherwise Unmarried.

Use of Converter

To use above created converter in you application, you need to create object of converter in resource, below code demonstrates how to use converter through XAML.

 <Window x:Class="ValueConverters.MainWindow"    
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
    xmlns:local="clr-namespace:ValueConverters"    
    Title="MainWindow" Height="350" Width="525">    
   <Window.Resources>    
    <local:ValueConverter x:Key="valueconverter"></local:ValueConverter>    
    <local:CheckBoxCheckConverter x:Key="checkBoxCheckConverter"></local:CheckBoxCheckConverter>    
   </Window.Resources>    
   <Grid>    
    <TextBlock Text="Value Converter Exampkle" HorizontalAlignment="Stretch" VerticalAlignment="Top" TextAlignment="Center"></TextBlock>    
    <TextBox Name="txtFirstName" HorizontalAlignment="Left" VerticalAlignment="Top" Height="36" Width="255" Margin="136,38,0,0" ></TextBox>    
    <Button Content="Click" HorizontalAlignment="Left" VerticalAlignment="Top" Height="23" Width="50" Margin="230,101,0,0" IsEnabled="{Binding Path=Text, ElementName=txtFirstName,Converter={StaticResource valueconverter}}"></Button>    
    <CheckBox Content="Married" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="307,108,0,0" IsChecked="{Binding Path=Text, ElementName=txtFirstName,Converter={StaticResource checkBoxCheckConverter}}"></CheckBox>    
    <TextBlock Text="MultiValue Converter Exampkle" HorizontalAlignment="Stretch" VerticalAlignment="Top" TextAlignment="Center" Margin="10,146,-10,0"></TextBlock>    
   </Grid>    
  </Window>    

The preceding code create object of converter in the windows resource and uses it with the binding element.

Related Articles

  1. Resource in WPF
  2. UpdateSourceTrigger
  3. WPF Binding
  4. WPF Style
  5. WPF Converters
  6. WPF MultiValue Converter
  7. WPF INotifyPropertyChanged Interface
  8. WPF DEPENDENCY PROPERTIES

Summary

In this article we have discussed details about Value converter with code example.Hope this article make you helpful.

Thanks