WPF: A simple IValueConverter implementation

In real life, we have always need to convert a value from one unit to another.  For example, we might need to convert inches into meters, Fahrenheit into Celsius etc.

The IValueConverter provides a way to apply custom conversion to a binding.

Value converters are culture-aware. Both the Convert and ConvertBack methods have a culture parameter that indicates the cultural information.  Those cultural information includes the language settings, location or date and time etc of your PC.

We look at an example where typing 0 will give us a false and typing 1 will give us a true.

MainWindow.xaml
<Window x:Class="ValueConverter.Window"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="clr-namespace:ValueConverter"
  Title="ValueConverter"
  Height="300"
  Width="300">
    <Window.Resources>
        <local:Converter x:Key="Converter" />
    </Window.Resources>
    <StackPanel Margin="10">
        <TextBox Name="tb" />
            <TextBlock Text="0:False, 1:True: " />
        <TextBlock Foreground="Blue" Text="{Binding ElementName=tb, Path=Text, Converter={StaticResource Converter}}"></TextBlock>
    </StackPanel>
</Window>

MainWindow.xaml
using System;
using System.Globalization;
using System.Windows.Data;

namespace ValueConverter
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    /// 

    public class Converter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value.ToString() == "1")
            {
                return true;
            }
            else
                return false;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if ((bool)value == true)
            {
                return "1";
            }
            else
                return "0";
        }
    }

    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

From the example above, you can see that we need to create a class Converter that implements the IValueConverter interface and then implement the Convert and ConvertBack methods.

converter

Series Navigation<< WPF: Data template for multiple similar data
WPF: Date conversion with IValueConverter >>