Wpf номер телефона

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}}" />

  • Remove From My Forums
  • Question

  • I am trying to format a phone number that is in the database in the form 5452626 to be 545-2626. I have tried several things including

    <TextBox Text=»{Binding CeoPhone, StringFormat=Phone{0:###-####}}» Name=»txtCeoPhone» Height=»25″ />
    The text «Phone» is put in for testing purposes.

    What I get is Phone5452626.

    Thanks

Answers

  • Hi Roger,

    the problem is that your phone-number probably is a String, which renders the StringFormat useless. Consider the following:

    <Window x:Class="WpfTests.XAML_TempExperiments"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        >
       <Window.Resources>
          <sys:Int32 x:Key="phoneNumber_AsInt32">5452626</sys:Int32>
          <sys:String x:Key="phoneNumber_AsString">5452626</sys:String>
       </Window.Resources>
       <StackPanel>
          <TextBlock Margin="5" 
                     Text="Using an Int32:"
                     FontWeight="Bold"/>
          <TextBlock Margin="5"
             Text="{Binding Source={StaticResource phoneNumber_AsInt32}, 
                StringFormat=Phone: {0:(000)-0000}}"/>
          <TextBlock Margin="5"
             Text="{Binding Source={StaticResource phoneNumber_AsInt32}, 
                StringFormat={0:000-0000}}"/>
    
          <TextBlock Margin="5,25,5,5" 
                     Text="Using a string:"
                     FontWeight="Bold"/>
          <TextBlock Margin="5"
             Text="{Binding Source={StaticResource phoneNumber_AsString}, 
                StringFormat=Phone: {0:(000)-0000}}"/>
          <TextBlock Margin="5"
             Text="{Binding Source={StaticResource phoneNumber_AsString}, 
                StringFormat={0:000-0000}}"/>
       </StackPanel>
    </Window>
    

    In the sample you can see that, if your phone number would i.e. be an Int32, a format could be applied. That said, you’ll either have to use a Converter instead or format the phone-number accordingly when you retrieve it from the DB.


    Cheers,
    Olaf

    • Marked as answer by

      Thursday, January 21, 2010 7:24 AM

Validating phone numbers is difficult, because the telephony authorities were too creative in how they used the limited available number range and because phone numbers look different in various countries. This article describes how phone number input validation can be reasonably done and provides a Control with production quality code, including letting the user enter only valid keystrokes, controlling if the phone number must be entered (required field) and alerting the user if he tries to close the window without saving the changes made. This control is part of the WpfWindowLib.

  • Download source code from Github

Table of Contents

  • Introduction
    • Phone Number Format
    • Country Code Structure
    • Formatting International Phone Numbers
    • Formatting Local Phone Numbers
  • Using the Code
  • Configuring PhoneTextBox
  • Static Class CountryCode
  • Getting the Code
  • Recommended Reading
  • History

Introduction

Writing a WPF control which validates phone numbers is a challenge, because the same phone number looks differently depending from which country it is dialled. The control must be flexible enough to meet your requirements, i.e., if you need strict control with precise formatting or if you just want to alert the user if he keyed in a funny looking phone number. Of course, best is if you prevent the user from making invalid input, and control which keystrokes he can make. Since this control is part of WpfWindowLib, it doesn’t let the user save the data if the phone number is required and missing. It also informs the user if he tries to close the window without saving the data.

Phone Number Format

How does a phone number look like? This really depends on where you live and in which year.

When I grew up near Zürich, phone numbers were short and simple

34 56 78 fictitious phone number dialled locally in Zürich
01 34 56 78 when dialled from outside Zürich
0041 1 34 56 78 when dialled from Germany

But Zürich got too big and the numbers changed to:

234 56 78 fictitious phone number dialled locally in Zürich
01 234 56 78 when dialled from outside Zürich
0041 1 234 56 78 when dialled from Germany

Switzerland needed more phone regions and the numbers changed again:

<s>234 56 78 fictitious phone number dialled locally in Zürich</s> no longer valid
044 234 56 78 when dialled from within Switzerland
0041 44 234 56 78 when dialled from Germany

Then came the mobile phones adding another variant:

+41 44 234 56 78 from outside Switzerland

The exact same number can be written in different ways:

0442345678
044-234 56 7
(044)234 56 78
044/234 56 78-123 with extension

And last but not least, different countries use different dialling for exactly the same phone number destination:

011 41 44 234 56 78 US
0111 41 44 234 56 78 Australia
0010 41 44 234 56 78 Bolivia
0015 41 44 234 56 78 Brazil

And don’t forget, there are also special numbers like 199, which follow a completely different format.

The consequence of this huge variety is that you have to choose if you want to give the user the freedom to key in all possible phone number notations or if you want to restrict the format, let’s say to the international format with the leading ‘+‘.

The PhoneTextBox control treats international and local phone numbers differently. If the entered phone number starts with ‘+‘, ‘00‘ or is longer than CountryCode.MaxLengthLocalCode (default=10), it is considered to be an international number. It then tries to detect any leading ‘+‘, ‘0‘ or ‘00‘ and removes them and any blanks or special characters. The next digits are the country code. Unfortunately, also the country code structure is a big mess!

Country Code Structure

Normally, the first 2 or 3 digits after the ‘+‘ specify the country. Exceptions are a leading ‘1‘ (USA, Canada and some smaller countries) and ‘9‘ (Russia and some smaller countries). The definition for a leading ‘1‘ is really messy:

1200
...
1339 USA
1340 Virgin Islands (Caribbean Islands)
1341 USA
1342 not used
1343 Canada
1344 Reserved
1345 Cayman Islands
1346 USA
...
1365 Canada
...
1999

For details, see this link.

Crazy right? But to format the phone number properly, one needs to know how long the country code is. For this purpose, I wrote the class CountryCode. Its method Country? GetCountry(string phoneNumber) returns the country and the country code length, if possible.

Formatting International Phone Numbers

CountryCode.Format() can be used to format local and international phone numbers. If it detects an international phone number, it will return it in the following format:

+ccc dddddddddd
  • ccc: country code, can be 2 to 4 digits
  • ddd: local code (including area code), any length
  • There will be exactly 1 blank, between country code and local code.
  • Exception: Of course, US and Canada. There is no country code separating these countries. In this case, ccc has 4 digits and indicates country and region.

Formatting Local Phone Numbers

As shown in my example, there are many ways how to write local phone numbers. Depending on the country you live in, you might want to write your own local phone number format method and assign it to CountryCode Func<string, string?>? LocalFormat. Or you can use one of the local format methods from CountryCode, which return different formatting depending on how many digits the phone number has:

LocalFormatNo0Area2(): 2 digit area code without leading 0

23-456 789
23-456 78 90
23-4567 8901

LocalFormat0Area2(): 2 digit area code with leading 0

023-456 789
023-456 78 90
023-4567 8901

LocalFormat0Area3(): 3 digit area code without leading 0

234-567 890
234-567 89 01
234-5678 9012

LocalFormat0Area3(): 3 digit area code with leading 0

0234-567 890
0234-567 89 01
0234-5678 9012

LocalFormat8Digits(): exactly 8 digits, no area code for countries like Singapore

1234 5678

Note: If a very short number is entered like 199, the entered format will not be changed.

Using the Code

<wwl:CheckedWindow x:Class="Samples.SampleWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wwl="clr-namespace:WpfWindowsLib;assembly=WpfWindowsLib"
                   SizeToContent="WidthAndHeight">
  <StackPanel>
    <Label Content="Phone No required"/>
    <wwl:PhoneTextBox x:Name="RequiredPhoneTextBox" MinWidth="100" MinDigits="7" 
       MaxDigits="13" IsRequired="True"/>
    <Label Content="Phone No  not required"/>
    <wwl:PhoneTextBox x:Name="NotRequiredPhoneTextBox" MinWidth="100"/>
    <Button x:Name="SaveButton" Content="_Save"/>
  </StackPanel>
</wwl:CheckedWindow>

Image 1

The upper window displayed is the data entry window with 2 PhoneTextBoxes. The first box is required, but the user has not entered any data yet, that’s why the background is khaki. That is also the reason why the Save Button is disabled. The user has entered a number into the second PhoneTextBox. The user tried then to close the window without saving the data. A second window with a warning opened and the second PhoneTextBox‘s background got light green, to show the user which data has changed. For a detailed explanation of how this works, see my article, Base WPF Window Functionality for Data Entry.

Configuring PhoneTextBox

In many cases, you don’t need to configure anything. You might want to set IsRequired, MinDigits and MaxDigits in XAML or, if the user wants to edit some existing data, call Initialise() passing the existing phone number as parameters from code behind.

Instance Properties

Some properties can be set individually for every PhoneTextBox:

  • MinDigits (DependencyProperty): How many digits a user needs to enter before leaving the PhoneTextBox. Only characters between ‘0‘ and ‘9‘ get counted.
  • MaxDigits (DependencyProperty): How many digits the user can maximally enter.
  • IsRequired (DependencyProperty): Needs the user to provide this control with a value?
  • CompactNumber (normal property): When storing the phone number, it might be convenient to store every phone with number digits only. This simplifies searches, indexing, etc. CompactNumber can only be read and only from code (not XAML).

Static Properties

Some properties apply for every PhoneTextBox and are therefore declared as static:

  • LegalSpecialCharacters: digits and one leading ‘+‘ can always be entered. Per default, also ‘-‘ and ‘/‘ can be used. If it should be possible to also enter other characters, change LegalSpecialCharacters accordingly.
  • ValidateUserInput (Func<> property): gets called every time a user has keyed in a character, except when he enters a blank. Assign a different method to change how user input gets validated. Normally, you don’t need to do that.
  • ValidatePhoneNumber (Delegate property): gets called when the user wants to move to the next controls (PreviewLostKeyboardFocus) and validates if phoneNumber is a valid phone number. When returning, compactNumber might have been updated.

Static Class CountryCode

I moved the country area specific code in its own class. It stores country specific information like Name, international dialling code and 2 and 3 letter abbreviations of the country name in 2 collections:

SortedDictionary<string, Country> ByAbbreviation3;
DigitInfo?[] ByPhone;

CountryCode.ByPhone holds like a dictionary all countries, indexed by their phone country code. But the storage is very different. The very first digit of the country code points to a DigitInfo.

public class DigitInfo {
  public char Digit;
  public Country? Country;
  public DigitInfo?[]? Digits;
}

The second digit is used as index into DigitInfo.Digits, which returns another DigitInfo. Once all digits of a country code are use, the country is found. Examples:

country code 1: byPhone[1].Country is US
country code 1236: byPhone[1].Digits[2].Digits[3].Digits[6].Country is Canada
country code 1235: byPhone[1].Digits[2].Digits[3].Digits[5].Country is null. Since 
                   byPhone[1].Country is US, also 1235 is US, because no other 
                   country was found in the later digits

This complicated structure is needed to cater for all country code variations. Usually, one does not access ByPhone directly, that would be too complicated. Instead, one calls CountryCode.GetCountry(string phoneNumber).

Configuring CountryCode

  • MaxLengthLocalCode: Number of digits a local phone code (including area code) can maximal have. If more digits are provided, number is considered to be an international dialling code. Default is 10 (2 area code and 8 local digits).
  • DefaultFormat (Func<string, string>): Formats a phone number. Assign your own Format() method, if you have special requirements. CountryCode.DefaultFormat() works like this: If phone number starts with ‘+‘ or «00» or is longer than MaxLengthLocalCode, it is formatted like an international dialling code, i.e., ‘+‘ country-code local-code. If it is not international, CountryCode.LocalFormat() is called for formatting.
  • LocalFormat (Func<string, string?>): holds the function being used for formatting a local phone number (i.e., not an international dialling code). You can provide your own method or use one from CountryCode (see description in Formatting local phone numbers):
    • LocalFormatNo0Area2()
    • LocalFormat0Area2()
    • LocalFormatNo0Area3()
    • LocalFormat0Area3()
    • LocalFormat8Digits()

Getting the Code

The latest version is available from Github @ https://github.com/PeterHuberSg/WpfWindowsLib.

Download or clone everything to your PC, which gives you a solution WpfWindowsLib with the following projects:

  • WpfWindowsLib: (.Dll) to be referenced from your other solutions, contains PhoneTextBox
  • Samples: WPF Core application showing all WpfWindowsLib controls
  • WpfWindowsLibTest: with few WpfWindowsLib unit tests

Recommended Reading

  • Base WPF Window Functionality for Data Entry
  • Email Address Validation Explained in Detail
  • Guide to WPF DataGrid Formatting Using Bindings

History

  • 9th April, 2020: Initial version

This article, along with any associated source code and files, is licensed under A Public Domain dedication

Validating phone numbers is difficult, because the telephony authorities were too creative in how they used the limited available number range and because phone numbers look different in various countries. This article describes how phone number input validation can be reasonably done and provides a Control with production quality code, including letting the user enter only valid keystrokes, controlling if the phone number must be entered (required field) and alerting the user if he tries to close the window without saving the changes made. This control is part of the WpfWindowLib.

  • Download source code from Github

Table of Contents

  • Introduction
    • Phone Number Format
    • Country Code Structure
    • Formatting International Phone Numbers
    • Formatting Local Phone Numbers
  • Using the Code
  • Configuring PhoneTextBox
  • Static Class CountryCode
  • Getting the Code
  • Recommended Reading
  • History

Introduction

Writing a WPF control which validates phone numbers is a challenge, because the same phone number looks differently depending from which country it is dialled. The control must be flexible enough to meet your requirements, i.e., if you need strict control with precise formatting or if you just want to alert the user if he keyed in a funny looking phone number. Of course, best is if you prevent the user from making invalid input, and control which keystrokes he can make. Since this control is part of WpfWindowLib, it doesn’t let the user save the data if the phone number is required and missing. It also informs the user if he tries to close the window without saving the data.

Phone Number Format

How does a phone number look like? This really depends on where you live and in which year.

When I grew up near Zürich, phone numbers were short and simple

34 56 78 fictitious phone number dialled locally in Zürich
01 34 56 78 when dialled from outside Zürich
0041 1 34 56 78 when dialled from Germany

But Zürich got too big and the numbers changed to:

234 56 78 fictitious phone number dialled locally in Zürich
01 234 56 78 when dialled from outside Zürich
0041 1 234 56 78 when dialled from Germany

Switzerland needed more phone regions and the numbers changed again:

<s>234 56 78 fictitious phone number dialled locally in Zürich</s> no longer valid
044 234 56 78 when dialled from within Switzerland
0041 44 234 56 78 when dialled from Germany

Then came the mobile phones adding another variant:

+41 44 234 56 78 from outside Switzerland

The exact same number can be written in different ways:

0442345678
044-234 56 7
(044)234 56 78
044/234 56 78-123 with extension

And last but not least, different countries use different dialling for exactly the same phone number destination:

011 41 44 234 56 78 US
0111 41 44 234 56 78 Australia
0010 41 44 234 56 78 Bolivia
0015 41 44 234 56 78 Brazil

And don’t forget, there are also special numbers like 199, which follow a completely different format.

The consequence of this huge variety is that you have to choose if you want to give the user the freedom to key in all possible phone number notations or if you want to restrict the format, let’s say to the international format with the leading ‘+‘.

The PhoneTextBox control treats international and local phone numbers differently. If the entered phone number starts with ‘+‘, ‘00‘ or is longer than CountryCode.MaxLengthLocalCode (default=10), it is considered to be an international number. It then tries to detect any leading ‘+‘, ‘0‘ or ‘00‘ and removes them and any blanks or special characters. The next digits are the country code. Unfortunately, also the country code structure is a big mess!

Country Code Structure

Normally, the first 2 or 3 digits after the ‘+‘ specify the country. Exceptions are a leading ‘1‘ (USA, Canada and some smaller countries) and ‘9‘ (Russia and some smaller countries). The definition for a leading ‘1‘ is really messy:

1200
...
1339 USA
1340 Virgin Islands (Caribbean Islands)
1341 USA
1342 not used
1343 Canada
1344 Reserved
1345 Cayman Islands
1346 USA
...
1365 Canada
...
1999

For details, see this link.

Crazy right? But to format the phone number properly, one needs to know how long the country code is. For this purpose, I wrote the class CountryCode. Its method Country? GetCountry(string phoneNumber) returns the country and the country code length, if possible.

Formatting International Phone Numbers

CountryCode.Format() can be used to format local and international phone numbers. If it detects an international phone number, it will return it in the following format:

+ccc dddddddddd
  • ccc: country code, can be 2 to 4 digits
  • ddd: local code (including area code), any length
  • There will be exactly 1 blank, between country code and local code.
  • Exception: Of course, US and Canada. There is no country code separating these countries. In this case, ccc has 4 digits and indicates country and region.

Formatting Local Phone Numbers

As shown in my example, there are many ways how to write local phone numbers. Depending on the country you live in, you might want to write your own local phone number format method and assign it to CountryCode Func<string, string?>? LocalFormat. Or you can use one of the local format methods from CountryCode, which return different formatting depending on how many digits the phone number has:

LocalFormatNo0Area2(): 2 digit area code without leading 0

23-456 789
23-456 78 90
23-4567 8901

LocalFormat0Area2(): 2 digit area code with leading 0

023-456 789
023-456 78 90
023-4567 8901

LocalFormat0Area3(): 3 digit area code without leading 0

234-567 890
234-567 89 01
234-5678 9012

LocalFormat0Area3(): 3 digit area code with leading 0

0234-567 890
0234-567 89 01
0234-5678 9012

LocalFormat8Digits(): exactly 8 digits, no area code for countries like Singapore

1234 5678

Note: If a very short number is entered like 199, the entered format will not be changed.

Using the Code

<wwl:CheckedWindow x:Class="Samples.SampleWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wwl="clr-namespace:WpfWindowsLib;assembly=WpfWindowsLib"
                   SizeToContent="WidthAndHeight">
  <StackPanel>
    <Label Content="Phone No required"/>
    <wwl:PhoneTextBox x:Name="RequiredPhoneTextBox" MinWidth="100" MinDigits="7" 
       MaxDigits="13" IsRequired="True"/>
    <Label Content="Phone No  not required"/>
    <wwl:PhoneTextBox x:Name="NotRequiredPhoneTextBox" MinWidth="100"/>
    <Button x:Name="SaveButton" Content="_Save"/>
  </StackPanel>
</wwl:CheckedWindow>

Image 1

The upper window displayed is the data entry window with 2 PhoneTextBoxes. The first box is required, but the user has not entered any data yet, that’s why the background is khaki. That is also the reason why the Save Button is disabled. The user has entered a number into the second PhoneTextBox. The user tried then to close the window without saving the data. A second window with a warning opened and the second PhoneTextBox‘s background got light green, to show the user which data has changed. For a detailed explanation of how this works, see my article, Base WPF Window Functionality for Data Entry.

Configuring PhoneTextBox

In many cases, you don’t need to configure anything. You might want to set IsRequired, MinDigits and MaxDigits in XAML or, if the user wants to edit some existing data, call Initialise() passing the existing phone number as parameters from code behind.

Instance Properties

Some properties can be set individually for every PhoneTextBox:

  • MinDigits (DependencyProperty): How many digits a user needs to enter before leaving the PhoneTextBox. Only characters between ‘0‘ and ‘9‘ get counted.
  • MaxDigits (DependencyProperty): How many digits the user can maximally enter.
  • IsRequired (DependencyProperty): Needs the user to provide this control with a value?
  • CompactNumber (normal property): When storing the phone number, it might be convenient to store every phone with number digits only. This simplifies searches, indexing, etc. CompactNumber can only be read and only from code (not XAML).

Static Properties

Some properties apply for every PhoneTextBox and are therefore declared as static:

  • LegalSpecialCharacters: digits and one leading ‘+‘ can always be entered. Per default, also ‘-‘ and ‘/‘ can be used. If it should be possible to also enter other characters, change LegalSpecialCharacters accordingly.
  • ValidateUserInput (Func<> property): gets called every time a user has keyed in a character, except when he enters a blank. Assign a different method to change how user input gets validated. Normally, you don’t need to do that.
  • ValidatePhoneNumber (Delegate property): gets called when the user wants to move to the next controls (PreviewLostKeyboardFocus) and validates if phoneNumber is a valid phone number. When returning, compactNumber might have been updated.

Static Class CountryCode

I moved the country area specific code in its own class. It stores country specific information like Name, international dialling code and 2 and 3 letter abbreviations of the country name in 2 collections:

SortedDictionary<string, Country> ByAbbreviation3;
DigitInfo?[] ByPhone;

CountryCode.ByPhone holds like a dictionary all countries, indexed by their phone country code. But the storage is very different. The very first digit of the country code points to a DigitInfo.

public class DigitInfo {
  public char Digit;
  public Country? Country;
  public DigitInfo?[]? Digits;
}

The second digit is used as index into DigitInfo.Digits, which returns another DigitInfo. Once all digits of a country code are use, the country is found. Examples:

country code 1: byPhone[1].Country is US
country code 1236: byPhone[1].Digits[2].Digits[3].Digits[6].Country is Canada
country code 1235: byPhone[1].Digits[2].Digits[3].Digits[5].Country is null. Since 
                   byPhone[1].Country is US, also 1235 is US, because no other 
                   country was found in the later digits

This complicated structure is needed to cater for all country code variations. Usually, one does not access ByPhone directly, that would be too complicated. Instead, one calls CountryCode.GetCountry(string phoneNumber).

Configuring CountryCode

  • MaxLengthLocalCode: Number of digits a local phone code (including area code) can maximal have. If more digits are provided, number is considered to be an international dialling code. Default is 10 (2 area code and 8 local digits).
  • DefaultFormat (Func<string, string>): Formats a phone number. Assign your own Format() method, if you have special requirements. CountryCode.DefaultFormat() works like this: If phone number starts with ‘+‘ or «00» or is longer than MaxLengthLocalCode, it is formatted like an international dialling code, i.e., ‘+‘ country-code local-code. If it is not international, CountryCode.LocalFormat() is called for formatting.
  • LocalFormat (Func<string, string?>): holds the function being used for formatting a local phone number (i.e., not an international dialling code). You can provide your own method or use one from CountryCode (see description in Formatting local phone numbers):
    • LocalFormatNo0Area2()
    • LocalFormat0Area2()
    • LocalFormatNo0Area3()
    • LocalFormat0Area3()
    • LocalFormat8Digits()

Getting the Code

The latest version is available from Github @ https://github.com/PeterHuberSg/WpfWindowsLib.

Download or clone everything to your PC, which gives you a solution WpfWindowsLib with the following projects:

  • WpfWindowsLib: (.Dll) to be referenced from your other solutions, contains PhoneTextBox
  • Samples: WPF Core application showing all WpfWindowsLib controls
  • WpfWindowsLibTest: with few WpfWindowsLib unit tests

Recommended Reading

  • Base WPF Window Functionality for Data Entry
  • Email Address Validation Explained in Detail
  • Guide to WPF DataGrid Formatting Using Bindings

History

  • 9th April, 2020: Initial version

This article, along with any associated source code and files, is licensed under A Public Domain dedication

Favorskij

-19 / 23 / 8

Регистрация: 27.07.2010

Сообщений: 496

1

25.10.2015, 16:14. Показов 7774. Ответов 6

Метки нет (Все метки)


TextBox для номера телефона. Что бы туда указывали только цифры и не более 10 символов.
Как сделать?

Спасибо.

XML
1
<TextBox x:Name="textBox1" HorizontalAlignment="Left" Margin="335,0,0,243" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Bottom"/>

Добавлено через 7 минут
Просто я указываю <TextBox MaxLines=»5″ />
а мне ошибку выдает что такого синтекса не найдено

Добавлено через 1 минуту
Так, часть ответа нашел. Нужно указывать MaxLength=»5″

Добавлено через 6 минут
Вот тут вот пишут Реализовать ввод в textbox только цифр
Но только я не могу понять куда это вставлять.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



6stprod

http://jokenews.ru/

10 / 10 / 7

Регистрация: 07.02.2013

Сообщений: 179

26.10.2015, 17:51

2

Цитата
Сообщение от Favorskij
Посмотреть сообщение

Но только я не могу понять куда это вставлять.

C#
1
2
3
4
5
6
7
8
9
10
        public MainWindow()
        {
            InitializeComponent();
            textBox1.PreviewTextInput += new TextCompositionEventHandler(textBox_PreviewTextInput);
        }
 
        void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!Char.IsDigit(e.Text, 0)) e.Handled = true;
        }

Вам нужно создать событие «PreviewTextInput» для Вашего текстБокса



1



-19 / 23 / 8

Регистрация: 27.07.2010

Сообщений: 496

27.10.2015, 18:10

 [ТС]

3

6stprod Спасибо большое. Я чуть позже все это дело проверю. Просто вот из за этой Ошибка при создании приложения для настольных и мобильных устройств проблемы мне сейчас придется заново все делать по отдельности. Из за этой проблемы я не могу реализовать нужное.



0



-19 / 23 / 8

Регистрация: 27.07.2010

Сообщений: 496

27.10.2015, 21:37

 [ТС]

4

Цитата
Сообщение от 6stprod
Посмотреть сообщение

Вам нужно создать событие «PreviewTextInput» для Вашего текстБокса

Нет такого события в программе у меня

TextBox для номера телефона. Что бы туда указывали только цифры и не более 10 символов. Как?



0



6stprod

http://jokenews.ru/

10 / 10 / 7

Регистрация: 07.02.2013

Сообщений: 179

28.10.2015, 00:00

5

Favorskij, это довольно странно, я выделил текстбокс и вот

C#
1
2
3
4
5
ТекстБокснейм.PreviewTextInput += new TextCompositionEventHandler(textBox_PreviewTextInput);
void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!Char.IsDigit(e.Text, 0)) e.Handled = true;
        }

как то так)

Изображения

 



0



burning1ife

1458 / 1280 / 293

Регистрация: 21.09.2008

Сообщений: 3,438

Записей в блоге: 9

28.10.2015, 01:08

6

Favorskij, попробуйте сделать через Masked Textbox Behavior



0



-19 / 23 / 8

Регистрация: 27.07.2010

Сообщений: 496

02.11.2015, 02:25

 [ТС]

7

kenny69 Спасибо большое, я это все буду пробовать.

6stprod Мне тоже странно почему у меня нет. У меня стоит Visual Studio 2015 interprise.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

02.11.2015, 02:25

Помогаю со студенческими работами здесь

Как вводить в TextBox только цифры , и как ограничить длину текста в TextBox’e
Здравствуйте , уважаемые программисты. Назрел такой вот вопросик : есть несколько TextBox’ов , на…

Как сдвинуть вправо и вниз цифры номера телефона через html код
В шапке сайта необходимо переместить номер тел, какой html код для этого прописать?

как сделать что бы в textBox можно было вводить только цифры, «,» и «-«
как сделать что бы в textBox можно было вводить только цифры, &quot;,&quot; и &quot;-&quot;

Как получить только цифры из textbox?
КАК получить только цифр из TextBox

Как вводить в textBox только цифры или буквы
Здравствуйте. Только начинаю учиться программированию, возник такой вопрос. Как на форме в textbox…

Как разрешить вводить в TextBox только 3 цифры, а остальные не вводились?
как разрешить вводить в textbox только 3 цифры, а остальные не вводились?

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

7

Вопрос:

У меня есть DataGrid в окне WPF. Как я могу отобразить столбец строки номера телефона в DataGrid в формате “(999) 999-9999”?

В столбце Номер телефона в DataGrid используется TextBlock в CellTemplate и TextBox в CellEditingTemplate. Номер телефона сохраняется как строка без формации, например “9995551234”.

Можно ли отобразить телефон как: (999) 555-1234 и отредактировать его как (999) 555-1234?

Лучший ответ:

Попробуйте использовать Text="{Binding PhoneNumber, StringFormat={}{0:(###)###-####}}"

Edit

Если ваше свойство PhoneNumber имеет строку типа, то нечего делать с StringFormat, чтобы отформатировать его.

В прошлом, когда я хотел сделать что-то вроде этого, я выставляю свойство с именем FormattedPhoneNumber, которое возвращает форматированный номер телефона для целей отображения, а поле редактирования просто связывается с простым старым неформатированным 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;
        }
    }
}

Ответ №1

Ответ №2

Я хотел бы продлить то, что уже ответила Рейчел. Если номер телефона является целым числом, StringFormat будет работать нормально. Если номер телефона является строкой, я нашел конвертер весьма удобным. Это устраняет необходимость создания дополнительного свойства для класса.

Вот пример:

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}}" />
  • Remove From My Forums
  • Question

  • I have a phone number textbox. I want to create a format as 0012 34 567 89 01 instead of 0012345678901. How can I make a solution for this in WPF. That would be good if I solve in c# side. 

    Thank you in advance


    KAdir

    • Edited by

      Wednesday, February 13, 2013 2:28 PM

Answers

  • Hi KAdir,

    If you want to set all this phone number to the same style:” 0012 34 567 89 01”, I would suggest you to clean all this format of numbers firstly and then give them the new format.

    Sample code like this:( assuming that you get the phone number from DB and put it into a textbox which named ”tb”)

    string[] split = textBox1.Text.Split(new char[] { '-', '(', ')' });// remove all old format,if your phone number is like(001)123-456-789 StringBuilder sb = new StringBuilder(); foreach (string s in split) { if (s.Trim() != "") { sb.Append(s); } } this.textBox1.Text = String.Format("{0:0000-00-000-00-00}", double.Parse(sb.ToString()));//you will get 0001-12-345-67-89

    Regards,


    Lisa Zhu [MSFT]
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Edited by
      Lisa Zhu
      Thursday, February 14, 2013 3:02 AM
    • Marked as answer by
      Omnipotent06
      Thursday, February 14, 2013 7:54 AM

  • Remove From My Forums
  • Question

  • I have a phone number textbox. I want to create a format as 0012 34 567 89 01 instead of 0012345678901. How can I make a solution for this in WPF. That would be good if I solve in c# side. 

    Thank you in advance


    KAdir

    • Edited by

      Wednesday, February 13, 2013 2:28 PM

Answers

  • Hi KAdir,

    If you want to set all this phone number to the same style:” 0012 34 567 89 01”, I would suggest you to clean all this format of numbers firstly and then give them the new format.

    Sample code like this:( assuming that you get the phone number from DB and put it into a textbox which named ”tb”)

    string[] split = textBox1.Text.Split(new char[] { '-', '(', ')' });// remove all old format,if your phone number is like(001)123-456-789 StringBuilder sb = new StringBuilder(); foreach (string s in split) { if (s.Trim() != "") { sb.Append(s); } } this.textBox1.Text = String.Format("{0:0000-00-000-00-00}", double.Parse(sb.ToString()));//you will get 0001-12-345-67-89

    Regards,


    Lisa Zhu [MSFT]
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Edited by
      Lisa Zhu
      Thursday, February 14, 2013 3:02 AM
    • Marked as answer by
      Omnipotent06
      Thursday, February 14, 2013 7:54 AM

Это тоже интересно:

  • Wowketo24 номер телефона
  • Wow привязка аккаунта к номеру телефона
  • Wot смена номера телефона
  • Wot как поменять номер телефона если старый потерял
  • World of tanks blitz номер телефона техподдержка

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии