Thursday, November 21, 2013

Using IValue Converter


Description:

             Value converter needs to implement the IValueConverter interface. IValueConverter had 2 public method (Convert and ConvertBack) with object return type (can return any data type), each method had four parameter

Convert:

Modifies source data from view model before display in XAML
value:
Data going to be processed before display
targetType:
Type of data expected by the target
Parameter:
Optional parameter for conversion logic ex: not operator, convert true to false and vice versa.
culture:
current culture used

ConvertBack:

Modifies destination data from XAML before processing in view model
value:
Destination data being processed by method
targetType:
Data expected by source object
parameter:
Optional parameter for conversion logic
culture:
Current culture used in processing

When to use value converter

                 Value converters are mostly used in situation like conversion from one format to another format without modifying source data, widely used example like covert from  Celsius to Fahrenheit and vice versa.

Other example:

1. Conversion like from pounds to kilogram or gram etc.
2. Conversion from Boolean true to visibility and vice versa

Implementation:

              Let us implement simple temperature converter, which convert from Celsius to Fahrenheit and vice versa

Step 1: import System.Windows.Data and System.Globalization namespace.
Step 2: Add class file which inherit IValueConverter.
Step 3: Formula to convert from 
             Celsius to Fahrenheit is 37°C x  9/5 + 32 = 98.6°F and convert from 
             Fahrenheit to Celsius is (98.6°F  -  32)  x  5/9 = 37°C, 

Implement these two methods as below

public class TemperatureConverter:IValueConverter
    {
        /// <summary>
        /// Celsius to Fahrenheit
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is Int64)
            {
                Int64 currValue = (Int64)value;
                return ((currValue * 9) / 5) + 32;
            }
            return null;
        }

        /// <summary>
        /// Fahrenheit to Celsius
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is Int64)
            {
                Int64 currValue = (Int64)value;
                return ((currValue - 32) * 5) /9;
            }
            return null;           
        }
    }



Using Value Converter in XAML:

Step 1: Import the namespace of class to XAML
xmlns:codes="clr-namespace:IValueConverterImplementation.Codes"

Step 2: Import the Value convertor to UserControl Resources, so that it can be used in XAML
<codes:TemperatureConverter x:Name="TemperatureConverter" />

Step 3: Define Controls and used it in Converter, StaticResource property

Example:

Without converter:
<TextBlock Text="{Binding Temperature}" ></TextBlock>

With Converter:
<TextBlock Text="{Binding Temperature,Converter={StaticResource TemperatureConverter}}" ></TextBlock>

In Text="{Binding Temperature}", Temperature is Int64 value from ViewModel.




Project Sample:

In demo project, you can find more examples like
1. DateTimeConverter – to convert DateTime to Date or short date
2. TextConverter – to convert incoming string to Upper or Lower Case
3. BooleanToVisibleConverter – convert false to Collapsed and true to Visible


No comments:

Post a Comment