I have created a custom control inheriting TextBox
. This custom control is a numeric TextBox
, only supporting numbers.
I am using OnPreviewTextInput
to check each new character being typed to see if the character is a valid input. This works great. However, if I paste the text into the TextBox
, OnPreviewTextInput
is not fired.
What is the best way to capture pasted text in a TextBox
?
Also, I have a problem when the back space is pressed, I can't figure out what event this will fire. OnPreviewTextInput
is not fired!
Any ideas how to capture pasted text and back space events in WPF TextBox
?
You can achieve this with
PreviewKeyDown
event andTextChanged
event.In
PreviewKeyDown
capture the Paste operationIn
TextChanged
eventWhere
IsNumber
method validates the entered text is Number or notThe trouble with trying to intercept and trap all the individual events that might cause a TextBox.Text property to change is that there are many such events:
Trying to reliably intercept all of these is an exercise in futility. A much better solution is to monitor TextBox.TextChanged and reject changes that you don't like.
In this answer I show how to implement a TextBoxRestriction class for the particular scenario being asked about. This same technique can be generalized for use with any restrictions you want to place on your TextBox control.
For example, in your case you might implemnt a
RestrictValidChars
attached property similarly to theRestrictDeleteTo
property in that code. It would be the same except that the inner loop would check inserts, not deletes. It would be used like this:This is just an idea of how it could be handled. There are many ways to structure your code depending on what you want. For example you could change TextBoxRestriction to call your own code to validate using an attached property that takes a delegate or an object containing an event.
See the other answer for details on how to bind the Text property when you are using the TextBoxRestriction class so it won't trigger the restriction when you don't want it to.
This works pretty good for me. I wanted to changed the color of the textbox when the user made a change to the contents.
I was able to achieve it with the 3 events below:
This might not be the exact answer your looking for but here is how to handle pasted text (this also works if user pasted using a the context menu):
For handling backspace use PreviewKeyDown event.
For backspace, please check the PreviewKeyDown event
For paste command, add a command binding to the ApplicationCommands.Paste, and set the argument to handled, if you do not wish to do anything with it:
And in code behind:
Here's some code I had lying around in case I ever needed it. Might help you.