Search code examples
c#.netwpftextbox

Cancelling a WPF TextBox Changed Event


I'm in the process of learning WPF coming from WinForms development.

I have a TextChanged event assigned to one of my TextBox's in my WPF application. If the user enters invalid data, I want to be able to revert to the previous text value.

In the old forms day, I would replace NewValue with OldValue, but it seems WPF doesn't work the same way.

Any ideas on what I could do it achieve this? Am I just not thinking with WPF yet?

Thanks.


Solution

  • You can do this two ways:

    1. Listen to the PreviewTextInput event and set e.Handled = true to stop the TextChanged event.

    2. Use WPF validation. There is a great post by Paul Stovell on Codeproject and a recent post on his blog.

    Those articles will get you started. one thing that got stuck with when I first did validation is that the validation rule only runs when the binding updates the source.