wpf

Format TextBox for phone number in WPF


I have a DataGrid in a WPF window. How can I display a phone number string column in the DataGrid in a format of "(999)999-9999"?

The Phone number column in the DataGrid uses a TextBlock in the CellTemplate and a TextBox in the CellEditingTemplate. The phone number is stored as a string with no formatting such as "9995551234".

Is it possible to display the phone as: (999)555-1234 and edit it as (999)555-1234?


Solution

  • Try using Text="{Binding PhoneNumber, StringFormat={}{0:(###)###-####}}"

    Edit

    If your PhoneNumber property is of type string, then there's not really a lot you can do with StringFormat to format it.

    In the past when I've wanted to do something like this, I expose a property called FormattedPhoneNumber which returns the formatted phone number for display purposes, and the edit box just binds to plain old unformatted PhoneNumber

    public string FormattedPhoneNumber
    {
        get
        {
            if (PhoneNumber == null)
                return string.Empty;
    
            switch (PhoneNumber.Length)
            { 
                case 7:
                    return Regex.Replace(PhoneNumber, @"(\d{3})(\d{4})", "$1-$2");
                case 10:
                    return Regex.Replace(PhoneNumber, @"(\d{3})(\d{3})(\d{4})", "($1) $2-$3");
                case 11:
                    return Regex.Replace(PhoneNumber, @"(\d{1})(\d{3})(\d{3})(\d{4})", "$1-$2-$3-$4");
                default:
                    return PhoneNumber;
            }
        }
    }