#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
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Pingback: Dew Drop – November 7, 2013 (#1662) | Morning Dew

  2. Pingback: #948 – Complete Example of Limiting TextBox Input | 2,000 Things You Should Know About WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: