I currently have a requirement to notify my application user if any fields have been changed/updated on a View.
For example, if the user changes a date field on the View and then tries to close the View, the application would display a message asking the user to Continue and lose changes or Cancel so that they can click the Save button.
Problem is: How do I detect that any of the data fields changed in the View?
Hope this makes sense, than you in advance, regards,
One approach you can take is to leverage the
IChangeTrackingandINotifyPropertyChangedinterfaces.If you create an abstract base class that your view models inherit from (
ViewModelBase) which implements theIChangeTrackingandINotifyPropertyChangedinterfaces, you can have your view model base attach to notification of property changes (in effect signaling that the view model has been modified) and which will set theIsChangedproperty to true to indicate that the view model is ‘dirty’.Using this approach, you are relying on property change notification via data binding to track changes and would reset the change tracking after any commits are made.
In the case you described you could handle the
UnloadedorClosingevent of your view to inspect theDataContext; and if the DataContext implementsIChangeTrackingyou can use the IsChanged property to determine if any unaccepted changes have been made.Simple example: