Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format TextBox for phone number in WPF

Tags:

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 formating such as "9995551234".

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

like image 380
Jerry Avatar asked Nov 10 '11 19:11

Jerry


2 Answers

I would like to extend what already Rachel has responded. If a phone number is an integer, StringFormat would work just fine. In case a phone number is a string, I found Converter to be quite handy. This removes the need to create additional property for a class.

Here is an example:

public class StringToPhoneConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return string.Empty;

        //retrieve only numbers in case we are dealing with already formatted phone no
        string phoneNo = value.ToString().Replace("(", string.Empty).Replace(")", string.Empty).Replace(" ", string.Empty).Replace("-", string.Empty);

        switch (phoneNo.Length)
        {
            case 7:
                return Regex.Replace(phoneNo, @"(\d{3})(\d{4})", "$1-$2");
            case 10:
                return Regex.Replace(phoneNo, @"(\d{3})(\d{3})(\d{4})", "($1) $2-$3");
            case 11:
                return Regex.Replace(phoneNo, @"(\d{1})(\d{3})(\d{3})(\d{4})", "$1-$2-$3-$4");
            default:
                return phoneNo;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }
}

xaml:

<TextBox Text="{Binding SelectedParticipant.PhoneNumber, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource StringToPhoneConverter}}" />
like image 112
lucas Avatar answered Sep 22 '22 00:09

lucas


after a short google search i found this two links the second one is in german

WPF – Masked Textbox Behavior http://marlongrech.wordpress.com/2007/10/28/masked-textbox/

Masked TextBox http://blindmeis.wordpress.com/2010/06/01/wpf-masked-textbox-behavior/

hope this helps

like image 21
punker76 Avatar answered Sep 24 '22 00:09

punker76