TextBox format for phone number in WPF

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

The DataGrid's Phone Number column uses a TextBlock in a CellTemplate and a TextBox in a CellEditingTemplate. The phone number is saved as a string without a formation, for example, "9995551234".

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

+7
source share
3 answers

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

Edit

If your PhoneNumber property has a type string, then there is nothing to do with StringFormat to format it.

In the past, when I wanted to do something like this, I set up a property called FormattedPhoneNumber that returns a formatted phone number for display purposes, and the edit box just links to a 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; } } } 
+7
source

after a short google search i found these two links the second one is in German

WPF - masked text field behavior http://marlongrech.wordpress.com/2007/10/28/masked-textbox/

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

hope this helps

+2
source

I would like to extend what Rachel already answered. If the phone number is an integer, StringFormat will work fine. If the phone number is a string, I found the converter quite convenient. This eliminates the need to create an additional property for the 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}}" /> 
0
source

All Articles