Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class PhoneTextBox : TextBox
- {
- public string CountryCode
- {
- get { return (string)GetValue(CountryCodeProperty); }
- set { SetValue(CountryCodeProperty, value); }
- }
- public static readonly DependencyProperty CountryCodeProperty =
- DependencyProperty.Register("CountryCode", typeof(string), typeof(PhoneTextBox), new PropertyMetadata(null, OnCountryCodeChanged));
- private static void OnCountryCodeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
- {
- var sender = (PhoneTextBox)d;
- var newValue = (string)e.NewValue;
- var oldValue = (string)e.OldValue;
- if (newValue != oldValue)
- {
- sender.Formatter = PhoneNumberUtil.GetInstance().GetAsYouTypeFormatter(newValue);
- sender.Text = sender.GetFormatted();
- sender.SelectionStart = sender.Text.Length;
- }
- }
- private AsYouTypeFormatter Formatter;
- protected override void OnKeyDown(KeyRoutedEventArgs e)
- {
- if (Formatter != null)
- {
- if (IsValidKey(e.Key))
- {
- Text = Text.Insert(SelectionStart, ValueFromKey(e.Key));
- Text = GetFormatted();
- SelectionStart = Text.Length;
- }
- else if (e.Key == VirtualKey.Back)
- {
- if (SelectionStart > 0)
- {
- Text = Text.Remove(SelectionStart - 1, 1);
- Text = GetFormatted();
- SelectionStart = Text.Length;
- }
- }
- }
- e.Handled = true;
- base.OnKeyDown(e);
- }
- private string GetFormatted()
- {
- Formatter.Clear();
- var text = Regex.Replace(Text, "[^0-9]", "");
- var result = string.Empty;
- for (int i = 0; i < text.Length; i++)
- {
- result = Formatter.InputDigit(text[i]);
- }
- return result;
- }
- private bool IsValidKey(VirtualKey key)
- {
- var name = Enum.GetName(typeof(VirtualKey), key);
- if (name.StartsWith("Number"))
- {
- return true;
- }
- return false;
- }
- private string ValueFromKey(VirtualKey key)
- {
- var name = Enum.GetName(typeof(VirtualKey), key);
- var value = Regex.Match(name, "([0-9])");
- return value.Value;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement