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


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

2 Responses to #632 – Block Input Using PreviewTextInput

  1. Pingback: Dew Drop – August 24, 2012 (#1,388) | Alvin Ashcraft's Morning Dew

  2. Pingback: #945 – A Strategy for Limiting Allowed Text in a TextBox | 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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: