1
Vote

Fix for MaskedTextBox - Not deleting all selected text from TextBox

description

Hello friends. I found a issue in MaskedTextBox and Fixed It !

The problem appears when you select all text in a MaskedTextBox (CTRL + A) and try to erase all text then.

What happens ? - The text isn't cleared, nothing happens...

The code below solve this problem found on "OnPreviewKeyDown" method.

P.S.: Please, if you found any problem on this fix, call me back.

(and sorry for bad english)
  protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            base.OnPreviewKeyDown(e);
           
            MaskedTextProvider provider = MaskProvider;
            
            int position = SelectionStart;
            
            if (e.Key == Key.Delete && position < Text.Length)
            {
                if (provider.RemoveAt(position))
                    RefreshText(provider, position);

                e.Handled = true;
            }

            else if (e.Key == Key.Space)
            {
                if (provider.InsertAt(" ", position))
                    RefreshText(provider, position);
                e.Handled = true;
            }

            //THE FIX ! If all text are selected and "Backspace" are pressed, clears the TextBox.
            else if (SelectedText.Length == Text.Length && e.Key == Key.Back) 
            {
                Text = provider.Replace(SelectedText,0).ToString();
            }

            else if (e.Key == Key.Back)
            {
                if (position > 0)
                {
                    position--;
                    if (provider.RemoveAt(position))
                        RefreshText(provider, position);
                }
                e.Handled = true;
            }
        }

comments