#948 – Complete Example of Limiting TextBox Input

If you want to limit text allowed as input to a TextBox, a full strategy for checking text being input should include handling the PreviewKeyDown and PreviewTextInput events, as well as implementing a pasting handler.  Below is a full example that limits text input to alphabetic characters only.

        <TextBox Name="txtMyText" Margin="5" Height="100"
                 TextWrapping="Wrap"
                 AcceptsReturn="True"
                 VerticalScrollBarVisibility="Auto"
                 PreviewTextInput="TextBox_PreviewTextInput"
                 PreviewKeyDown="TextBox_PreviewKeyDown"/>

 

        public MainWindow()
        {
            this.InitializeComponent();
            DataObject.AddPastingHandler(txtMyText, PasteHandler);
        }

        private bool IsAlphabetic(string s)
        {
            Regex r = new Regex(@"^[a-zA-Z]+$");

            return r.IsMatch(s);
        }

        private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            // Prohibit non-alphabetic
            if (!IsAlphabetic(e.Text))
                e.Handled = true;
        }

        private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            // Prohibit space
            if (e.Key == Key.Space)
                e.Handled = true;
        }

        private void PasteHandler(object sender, DataObjectPastingEventArgs e)
        {
            TextBox tb = sender as TextBox;
            bool textOK = false;

            if (e.DataObject.GetDataPresent(typeof(string)))
            {
                // Allow pasting only alphabetic
                string pasteText = e.DataObject.GetData(typeof(string)) as string;
                if (IsAlphabetic(pasteText))
                    textOK = true;
            }

            if (!textOK)
                e.CancelCommand();
        }
Advertisements

#945 – A Strategy for Limiting Allowed Text in a TextBox

You can limit the text that a user enters into a TextBox by handling the PreviewTextInput event and setting the TextCompositionEventArgs.Handled property to true for characters that you do not want to allow as input.

The PreviewTextInput event will not give you access to every possible keystroke that you might want to use in limiting input.  It’s not fired, for example, when the user presses the spacebar.

You often will also want to handle the PreviewKeyDown event to block keystrokes that don’t trigger PreviewTextInput.

Finally, you may want to intercept Paste events on a TextBox, in order to filter out text that you don’t want a user to paste into the TextBox.

A full strategy for limiting user-entered text might then include:

  • Handling PreviewTextInput and blocking undesirable text
  • Handling PreviewKeyDown and blocking undesirable keystrokes
  • Handling paste operations and blocking undesirable text

#638 – PreviewTextInput Is Not Fired In Many Cases

You’d normally use the PreviewTextInput event to filter data being entered into a text-based control like the TextBox.  But the PreviewTextInput event is fired for text that is being added to the control, but not fired for certain keypresses that could also result in changes to the text.

Key presses that do not result in the PreviewTextInput event being fired include:

  • Spacebar
  • Backspace
  • Home/End/Delete/Insert keys
  • Arrow keys
  • Control key combinations, including Ctrl+V

This means that if you were only validating text input in PreviewTextInput, a user could use Ctrl+V to do a paste operation into a TextBox and you wouldn’t get a chance to validate the text being added.

All of these key press do result in the PreviewKeyDown event being fired.  This means that to do complete validation of all changes to a TextBox, you’ll likely want to do some validation in PreviewTextInput and some additional validation in PreviewKeyDown.

#632 – Block Input Using PreviewTextInput

You can use the PreviewTextInput event for a control that accepts text input to block certain characters from being entered into the control.

To prevent a particular character from being entered into the control, simply set the Handled property of the TextCompositionEventArgs parameter to true.  This will intercept the event routing and will prevent the control from receiving the text.

<TextBox Text="" HorizontalAlignment="Center" Width="150"
     PreviewTextInput="TextBox_PreviewTextInput" />
    private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            // No e's allowed
            if ((e.Text == "e") || (e.Text == "E"))
                e.Handled = true;
        }

#630 – PreviewTextInput and TextInput Events

In addition to the four main keypress events–PreviewKeyDown, KeyDownPreviewKeyUp and KeyUp–an UIElement can fire two other events related to keyboard input.  Both fire when the user presses a key, or combination of keys, that results in the control receiving some text.  They do not fire when keys are pressed that don’t result in the keyboard sending text (e.g. the Backspace key).

Here’s the updated sequence of events:

  • PreviewKeyDown – tunneling
  • KeyDown – bubbling
  • PreviewTextInput  – tunneling
  • TextInput – bubbling
  • PreviewKeyUp – tunneling
  • KeyUp – bubbling

Note that controls that normally accept text and do something with it will suppress the TextInput event, marking it as handled.  For example, the TextBox control takes the text input and adds it to to the TextBox, so it marks TextInput as already handled.  The TextBox is saying that it already “handled” the text, so it doesn’t need to pass the event on to anybody else.