Being new to WPF & MVVM I struggling with some basic functionality.
Let me first explain what I am after, and then attach some example code...
I have a scree
In my experience, if you implement IsDirty
in your view model, you probably also want the view model to implement IEditableObject
.
Assuming that your view model is the usual sort, implementing PropertyChanged
and a private or protected OnPropertyChanged
method that raises it, setting IsDirty
is simple enough: you just set IsDirty
in OnPropertyChanged
if it isn't already true.
Your IsDirty
setter should, if the property was false and is now true, call BeginEdit
.
Your Save
command should call EndEdit
, which updates the data model and sets IsDirty
to false.
Your Cancel
command should call CancelEdit
, which refreshes the view model from the data model and sets IsDirty
to false.
The CanSave
and CanCancel
properties (assuming you're using a RelayCommand
for these commands) just return the current value of IsDirty
.
Note that since none of this functionality depends on the specific implementation of the view model, you can put it in an abstract base class. Derived classes don't have to implement any of the command-related properties or the IsDirty
property; they just have to override BeginEdit
, EndEdit
, and CancelEdit
.