When using textbox.Undo(); I get the following error:
Cannot Undo or Redo while undo unit is open.
Now I understand why this is the case (because it is an active undoable event) but through what event can I perform validation on a text box and undo the change if the user has typed an invalid character?
Instead of using Undo and TextChanged, you should use the
PreviewTextInputandDataObject.Pastingevents. In thePreviewTextInputevent handler, sete.Handledto true if the typed text is an invalid character. In thePastingevent handler, calle.CancelCommand()if the pasted text is invalid.Here is an example for a text box that accepts only the digits 0 and 1:
XAML:
Code behind: