How To Create A Value Converter Using IValueConverter In WPF

How To Create A Value Converter Using IValueConverter In WPF

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

When you design UI, sometimes you may find a scenario where you need to transform a value before it reaches its destination or back to its source again, you likely need a converter.

For example, while using WPF you may be binding the text property of a textbox with a property called 'CreditCardNumer'. When user inputs their credit card number in the screen, it will show something like:

4111111111111111

which is difficult to read if you want to check, you have entered correct credit card number.

To improve readability, you may want to show something like:

4111-1111-1111-1111

In WPF, we can achieve this conversion goal by implementing the IValueConverter interface.

Create a value converter

Let's implement a simple converter which takes a string as input and then returns an auto-format credit card number string, as well as the other way around.

public class CreditCardFormattingConverter: IValueConverter 
{
  /// <summary>
  /// Converts the object to a auto-format credit card number string
  /// </summary>
  /// <param name="value">The object to convert</param>
  /// <param name="targetType">unused</param>
  /// <param name="parameter">unused</param>
  /// <param name="culture">unused</param>
  /// <returns></returns>
  public Object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    var builder = new StringBuilder(Regex.Replace(value.ToString(), @ "\D", ""));

    foreach(var i in Enumerable.Range(0, builder.Length / 4).Reverse())
    {
      builder.Insert(4 * i + 4, "  ");
    }

    return builder.ToString().Trim();
  }

  /// <summary>
  /// Convert the object to original string value without formatting
  /// </summary>
  /// <param name="value">The object to convert</param>
  /// <param name="targetType">unused</param>
  /// <param name="parameter">unused</param>
  /// <param name="culture">unused</param>
  /// <returns></returns>
  public Object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return Regex.Replace(value.ToString(), @ "\D", "");
  }

}

Code explanation

This requires you to implement two methods: Convert() and ConvertBack(). As the name implies, these methods were used to convert the value to the destination format and then back again respectively.

You can see my below article for how to implement above value converter for credit card formatting in XAML:

 
Share this