What I did before was make a deep copy of the data object, then write a generic compare method that uses reflector to compares if there is difference betweens the two objects.
So say if I have a SaveButton, a TextBoxA binded with a ViewModel.PropertyA, initialy PropertyA is = “123”.
When user typed “1234” in TextBoxA, the PropertyA set method will executes the compare method to find the difference. And enable the Save Button.
But when the user changed the text “1234” back to “123”, the Save button will disabled again.
After 1 year, now I wonder is there a better way or easier way to do it?
i.e. Is there any framework that will do this kind of stuff? So I don’t have write code for deep copy the object, write compares method myself?
The actual UI I had was not that simple only contains TextBox type, that was a UI for edit customer information, thus have DateTime, Collection etc. That’s why I wrote deep copy method for cloning the whole object.
Assuming that these properties on your View Model are raising the
PropertyChangedevent somehow since the question is tagged withMVVM.Here’s one approach. Write an event handler for your ViewModel’s
PropertyChangedevent. Save original values in a privateDictionary<string, string>only when a property changes. That prevents the need for copying the whole object just in case someone makes an edit. If the property already exists in the dictionary, then you could easily determine if it’s been changed back to its original value.Edit: Oh, I was thinking that the
PropertyChangedEventArgscontained new and old values, but it doesn’t. So, in order to do this, you’d need to add some extra method call within your View Model’s property setters that can evaluate the old and new values of each property.In order to easily set up enabling and disabling the Save button, there should be a
boolproperty in your view model to which you would bind the Save button’s enabled property.If items are removed from the dictionary whenever the new value matches the original value, then your Save button enabled property could just return true if the dictionary contains any items.
Edit 2: For the collection types, you’d want to have your View bind to
ObservableCollectionproperties on your View Model. The Collection changed event does give you a list of old and new items, so keeping track of the changes within that event handler should be fairly easy.