To answer the simbay approach, which I think is fired.
You cannot invoke Undo in TextChanged because the undo operation is still being prepared by the TextBox. It seems that this works sometimes, and not at another time, so this suggests that there is a race condition between when the event is signaled and the cancellation is completed.
However, a Undo call called in Dispatcher will allow the text field to complete its undo preparation. You can check the results of the text change, and then decide whether you want to save or cancel the change. This may not be the best approach, but I tried it and blew up a bunch of text changes and inserts into the text box and couldn't throw an exception.
The โaccepted answerโ is great ONLY if you want to prevent the input or insertion of an invalid character, but overall I often do a much more active confirmation of the TextBox input and want to check the final value of the text. It is not easy to see the final text from the preview, because, as far as management is concerned, nothing has happened.
To answer the question of Terribad, the simbay answer is better and more concise in more situations.
tb.TextChanged =+ (sender, args ) => { if(! MeetsMyExpectations(tb.Text) ) Dispatcher.BeginInvoke(new Action(() => tb.Undo())); }
I read a lot of wild adventures in checking a text box, and it's about as simple as I found.
Chriscw
source share