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

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


  • kentuckerkentucker USMember ✭✭✭✭✭

    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

  • SherySharafSherySharaf Member

    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.

Sign In or Register to comment.