Skip to main content

WPF Value Converters

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. WPF Converters
  2. WPF MultiValue Converter
  3. WPF Binding

Summary

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

Thanks

Comments

Popular posts from this blog

Generate QR Code in WPF

Introduction In my previous two blogs, we have discussed how to display generate and display various barcodes on the web page. In this blog, we are going to demonstrate how to Generate QR Code in the WPF application. Getting Started Here in the demonstration Generate QR Code in WPF , will generate QR code using third party library as there is not inbuilt library provided by Microsoft to generate QR code and will display in WPF image control, In the below, we will see the steps to display QR Code. As I mentioned in the above paragraph that there is no inbuild library provided by Microsoft to generate QR code, I have taken the help of the ZXing library which is a third party free library and available Nuget. This library provides various options to generate barcodes and QR Code from the user-friendly text. Generate QR Code in WPF Here are the steps to generate QR code and let's follow the steps to complete demonstrations. Demonstration:- Generate QR Code Open visual stud

Creating Application in Prism

Introduction This article explains an illustration of creating a windows application in Prism Library(WPF Prism). The solution includes recommended practices and techniques and is the basis for the procedures in Prism. This illustration created in the Visual Studio 2012, It can also developed in the visual studio 2008 and 2010, because wpf supports from .net framework 3.5 to latest version. Microsoft.Practices.Prism.dll. This assembly contains the implementation of the Prism Library core components such as modularity, logging services, communication services, and definitions for several core interfaces. It also contains the implementation of Prism Library components that target WPF applications, including commands, regions, and events. Microsoft.Practices.Prism.UnityExtensions.dll. This assembly contains base and utility classes you can reuse in applications built with the Prism Library that consume the Unity Application Block. For example, it contains a bootstrapper base class

WPF Binding

Introduction This blog describes WPF Binding and the measure elements exist with binding with XAML example in XAML and code-behind. Getting Started Binding helps in WPF to flow data from one object to another object, the object which fetches data is called source and the object which receives the data is called target. The Object a be a UI control or object of a class that means in binding you can bind a property of a class and property of another control to WPF UI controls as well. XAML Example <TextBox x:Name="sourceText" Grid.Row="0" /> <Button Grid.Row="1" Content="{Binding ElementName=sourceText, Path=Text}"/> Code Example Button btn=new Button(); Binding binding = new Binding("Text"); binding.Source = sourceText; btn.SetBinding(Button.ContentProperty, binding); In WPF binding has some measure properties or elements that we are using while developing application or projects, here we are going to d