I have a form that is bind to an object, and when the user trying to leave the form, I want to warn them if anything on the form has been changed, and prompt them to save. My question is, is there any way to achieve this without implementing IComparar for all my classes in the binded object? I was thinking if there is a way I can serialize my object when loading the form, and do a simple comparison against the change object that also get serialized. Something like a string comparison.
Hope that make sense,
Thanks
To do what you’re trying to do, there is probably a much simpler method: Use a “modified” flag or event.
You can cascade this up many levels of user controls if need be. Just declare the event like this:
Then, at whatever level you need to actually check for modifications, hook all of the events.
Then all you have to do is check (and reset) the
isDataModifiedflag accordingly.It’s really not a lot of work, certainly easier than ensuring that
INotifyPropertyChangedis implemented for every object in the graph. Remember, this is a form, you don’t really care that the object changed, you care if the user made a change, and for that, you want to actually check for changes made through the controls.Yeah, it’s not perfect – you still run into the minor nuisance of reporting that data was changed even when the user changes something and then changes it back. But I don’t think I’ve ever actually heard a complaint about this, and using serialization as a comparison method just isn’t reliable. What you really need to do if you want to eliminate the redundant save confirmation is override the
Equalsmethod of every object in the graph and implement an actual value-equality operation. Or, if you don’t want to retain a copy of the old graph, use a checksum-generating function (collisions are possible but highly unlikely).But I would just stick with the flag. Don’t try to cheat your way out of writing equality checks. It’s actually sort of the same as trying to write an automatic deep-cloning method; you can try, but anything you come up with is going to be broken sometimes.