tags:

views:

4058

answers:

3

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.

+4  A: 

Read up about WPF validation.

http://stackoverflow.com/questions/63646/wpf-data-binding-and-validation-rules-best-practices has some good links.

Donnelle
By the way, that's not intended as a brush-off answer, just very busy guidance in the right direction!
Donnelle
+5  A: 

You can do this two ways:

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.

Dennis Roche
+1  A: 

I would use PreviewTextInput, most events in WPF have a Preview sibling. If you set the e.Handled = true it will stop the event from bubbelig/tunneling further.

I'm not sure if you are aware of it but Preview events are said to be tunneling, ie. they start from the outermost container and is posted in every container until it reaches the control that has focus. The non-preview events are said to be bubbeling, ie. they start at the control with focus, and is posted to every parent control.

If you set e.Handled = true on the outermost grid's PreviewTextChanged event, you cancel all other events including the TextChanged as well. First all Preview events get fired from the outermost to the control with focus, then all non-preview events get fired from the control with focus and out to the outermost parent control.

sindre j
Where is PreviewTextChanged? I can only find PreviewTextInput and TextChanged
Bryan
I'm not sure if it's been renamed or I was wrong in the first case, but the correct event is PreviewTextInput.
sindre j
Edited original answer to state PreviewTextInput, NOT PreviewTextChanged
sindre j