Return String formatted like a credit card number Using XAML And MVVM RRS feed

  • Question

  • User305799 posted

    How to set credit card number format In xaml Like 1234-1234-1234-1234

    Friday, March 24, 2017 10:14 AM

All replies

  • User96159 posted

    You can use an IValueConverter to format the output in a bound object. Or you can create a new property on the view model which has the formatted output


    Friday, March 24, 2017 12:17 PM
  • User366112 posted

    This can be easily achieved by using Value converters.

    public class CreditCardNumberValueConverter : IValueConverter
      public override 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();
      public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        return Regex.Replace(value.ToString(), @"\D", "");

    After initialising this in Styles.cs, you can apply it to the Text property of the control in XAML as:

    Text="{Binding CardNo, Converter={StaticResource CreditCardNumberValueConverter}}

    Likewise, Phone numbers too can also be formatted.

    Thursday, March 8, 2018 7:44 AM