#945 – A Strategy for Limiting Allowed Text in a TextBox
November 7, 2013 2 Comments
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