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.
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.