I want to track which character is deleted by the user through Delete or BackSpace Key.
I am handling TextBox_ChangedEvent of textbox.
Can I extract the deleted character from TextChangedEventArgs e.Changes and if yes How can I do that?
I want to restrict user to from deleting any characters from the TextBox. I want user can delete only two characters ( let's say "(" or ")" )
Please suggest.
I don't know WPF but assuming that it's same as WinForms for this (seems probable). The only way I know of is that you actually keep the current text in a variable and on text change, if it's not a delete or backspace, you update that text, otherwise you use it compare what's changed and if that change should be allowed.
Edit: Looking at
TextChangedEventArgs.Changes
it seems like the way I describe above might still be the way to go, but that you maybe could use theChanges
to compare the texts more efficiently.You might already have thought about it, but otherwise, remember to handle cut and paste also (and that the user might be doing that with the mouse rather than the keyboard).
An attached behaviour to handle it
Drop the behaviour in the resources section
Then in your textbox markup block, set the behaviour
Below you will find code for an attached property that can be used like this to prevent anything but "(" or ")" from being deleted from the TextBox, period.
This will correctly handle all mouse and keyboard updates, such as:
Because of this it is much more powerful than simply intercepting PreviewKeyDown.
This also disables deletion of anything byt "(" or ")" by assigning directly to the .Text property, so this will fail:
Because of this the TextBoxRestriction class also contains another attached property called UnrestrictedText which, when set, is able to update the Text property bypassing the restrictions. This can be set in code using
TextBoxRestriction.SetUnrestrictedText
, or data-bound like this:In the implementation below, UnrestrictedText only works when RestrictDeleteTo is also set. A full implementation could be made that registers the event handler whenever either property is set and saves the handler in a third attached property for later unregistration. But for your current needs that is probably unnecessary.
Here is the implementation as promised:
How it works: When you set UnrestrictedText it sets Text and vice versa. The TextChanged handler checks to see if Text is different than UnrestrictedText. If so, it knows that Text has been updated by some other mechanism than setting UnrestrictedText so is scans the changes for an illegal delete. If one is found it sets Text back to the value still stored in UnrestrictedText, preventing the change.