Posted by: Zeeshan Amjad | October 21, 2009

Using IValueConverter in Data Binding


Sometimes we need to store data in different format then we display it. In that situation we have to convert data from one format to another format. If we want to do data binding in that situation then we can use the Converter property of Binding class. This IValueConverter type property. Lets take a look at simple example.

IValueConverter is an interface that contains only two method. To implement this interface we have to give implementation of both methods. Here is a class diagram of this interface.

IValueConverter

Let’s take a look at our previous example to bind the enumerated value. Now we are going to make our convert. In this simple converter we simply upper the string and return it. Here is a code for this.

  1: [ValueConversion(typeof(Object), typeof(String))]
  2: public class TestConvertor : IValueConverter
  3: {
  4:     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  5:     {
  6:         if (value != null)
  7:         {
  8:             Enum str = value as Enum;
  9:             String strValue = str.ToString().ToUpper();
 10:             return strValue;
 11:         }
 12:         else
 13:             return value;
 14:     }
 15: 
 16:     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
 17:     {
 18:         return value;
 19:     }
 20: }
 21: 

Now if we want to use this convertor in XAML file then we will define it in Windows.Resource section.

  1: <odp:TestConvertor x:Key="testConverter"/>

Here odp is the namespace where we define our TestConvertor.

Here is a complete C# code of this.

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  5: using System.Windows;
  6: using System.Windows.Controls;
  7: using System.Windows.Data;
  8: using System.Windows.Documents;
  9: using System.Windows.Input;
 10: using System.Windows.Media;
 11: using System.Windows.Media.Imaging;
 12: using System.Windows.Navigation;
 13: using System.Windows.Shapes;
 14: using System.Reflection;
 15: using System.Globalization;
 16: 
 17: namespace objDataProvider
 18: {
 19:     /// <summary>
 20:     /// Interaction logic for Window1.xaml
 21:     /// </summary>
 22:     public partial class Window1 : Window
 23:     {
 24:         public Window1()
 25:         {
 26:             InitializeComponent();
 27:         }
 28:     }
 29: 
 30:     [ValueConversion(typeof(Object), typeof(String))]
 31:     public class TestConvertor : IValueConverter
 32:     {
 33:         public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 34:         {
 35:             if (value != null)
 36:             {
 37:                 Enum str = value as Enum;
 38:                 String strValue = str.ToString().ToUpper();
 39:                 return strValue;
 40:             }
 41:             else
 42:                 return value;
 43:         }
 44: 
 45:         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
 46:         {
 47:             return value;
 48:         }
 49:     }
 50: 
 51:     public enum StateInfo
 52:     {
 53:         California,     
 54:         Alaska,
 55:         RohdeIsland,
 56:         Wyoming
 57:     }
 58: }
 59: 

And here is XAML code for this project.

  1: <Window x:Class="objDataProvider.Window1"
  2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4:     xmlns:System="clr-namespace:System;assembly=mscorlib"
  5:     xmlns:odp="clr-namespace:objDataProvider"
  6:     Title="IValueConverter Example" Height="300" Width="400">
  7: 
  8:     <Window.Resources>
  9:         <odp:TestConvertor x:Key="testConverter"/>
 10:         <ObjectDataProvider x:Key="sateInfo"
 11:                     MethodName="GetValues" 
 12:                     ObjectType="{x:Type System:Enum}">
 13:             <ObjectDataProvider.MethodParameters>
 14:                 <x:Type TypeName="odp:StateInfo" />
 15:             </ObjectDataProvider.MethodParameters>
 16:         </ObjectDataProvider>
 17:     </Window.Resources>
 18: 
 19:     <ListBox Margin="5" HorizontalContentAlignment="Stretch" ItemsSource="{Binding Source={StaticResource sateInfo}}">
 20:         <ListBox.ItemTemplate>
 21:             <DataTemplate>
 22:                 <Border Margin="5" BorderBrush="DarkViolet" BorderThickness="2">
 23:                     <StackPanel Margin="5">
 24:                         <TextBlock FontWeight="Bold" Foreground="Blue" Text="{Binding}"/>
 25:                         <TextBlock Text="{Binding Converter={StaticResource testConverter}}"/>
 26:                     </StackPanel>
 27:                 </Border>
 28:             </DataTemplate>
 29:         </ListBox.ItemTemplate>
 30:     </ListBox>
 31: </Window>
 32: 

Here is the output of this progarm.

IValueConverter_02

We can also specify the rules inside the Convert or ConvertBack method. Here is one example to demonstrate this.

  1: [ValueConversion(typeof(Object), typeof(String))]
  2: public class TestConvertor : IValueConverter
  3: {
  4:     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  5:     {
  6:         if (value != null)
  7:         {
  8:             Enum str = value as Enum;
  9:             String strValue = str.ToString();
 10: 
 11:             switch (strValue)
 12:             {
 13:                 case "California":
 14:                     return "Largest state with respect to Population";
 15: 
 16:                 case "Alaska":
 17:                     return "Largest state with respect to Area";
 18: 
 19:                 case "RohdeIsland":
 20:                     return "Smallest state with respect to Area";
 21: 
 22:                 case "Wyoming":
 23:                     return "Smallest state with respect to Population";
 24: 
 25:             }                
 26:             return strValue;
 27:         }
 28:         else
 29:             return value;
 30:     }
 31: 
 32:     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
 33:     {
 34:         return value;
 35:     }
 36: }
 37: 

Here is the output of this program.

IValueConverter_03

Let’s take a look at one more example. Here we convert string into base64 encoding.

  1: [ValueConversion(typeof(Object), typeof(String))]
  2: public class TestConvertor : IValueConverter
  3: {
  4:     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  5:     {
  6:         if (value != null)
  7:         {
  8:             Enum str = value as Enum;
  9:             String strValue = str.ToString();
 10:             System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
 11: 
 12:             return System.Convert.ToBase64String(encoding.GetBytes(strValue));
 13:         }
 14:         else
 15:             return value;
 16:     }
 17: 
 18:     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
 19:     {
 20:         return value;
 21:     }
 22: }
 23: 
 24: 

Here is the output of this program.

IValueConverter_04

Advertisements

Responses

  1. […] We already saw the example of converter that changes the string from lower case to upper case here. And we also the the string encoding into base 64 using MVVM here. Let’s combine these two and […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: