views:

521

answers:

2

I have a basic form with controls that are databound to an object implementing the INotifyPropertyChanged interface. I would like to add some validation to a couple of properties but dont want to go through implementing IDataErrorInfo for the sake of validating a couple of properties.

I have created the functions that perform the validation and return the error message (if applicable) in the object. What I would like to do is call these functions from my form when the relevant properties on the object have changed, and setup the ErrorProvider control in my form with any error messages that have been returned from the validation functions.

I have tried hooking up event handlers to the Validating and LostFocus events, but these seem to fire before my object is updated, and hence they are not validating the correct data. Its only when I leave the textbox, go back in and then leave again that the validation runs against the correct data.

Is there another event that I can hook into so that I can call these validation functions after the property on my object has been updated? Or am I better off just implementing the IDataErrorInfo interface?

A: 

I'm not sure exactly what the problem is, are you saying that you can't get the property to set until the control looses focus?

If so, you need to set the binding to update OnPropertyChanged instead of OnValidation.

Binding to OnPropertyChanged means the binding is updated immediately, while OnValidation only updates the underlying object when a Validation is triggered (which for most controls is when they loose focus).

Cameron MacFarland
im fine with the property being set when the control looses focus, what I then want to do is attach to an event on my textboxes that fire when the property has updated so I can call the validation functions
KevB
I'd just handle the TextChanged event (on a Textbox) then. Or you could hook into the INotifyPropertyChanged event of your object.
Cameron MacFarland
+1  A: 

I think i've found a solution to the problem with the help of Cameron's post. I have changed the binding to update OnPropertyChanged and now when I wire up the event handler to the LostFocus event the validation is being performed on the "new" value from the textbox rather than what was previously held in the object

KevB