Skip to content

MVVM Models

Jan M edited this page Aug 12, 2020 · 2 revisions

Working with the ModelBase

The ModelBase is an extension of the BindingBase that adds the following functionalities:

  • IsDirty property indicating wether another property of the model has changed recently
  • LastPropertySet holding the name of the property changed the most recent (and changed IsDirty)
  • CommitChanges() and ResetChanges() methods that allow you to always keep a consistent state

I will go through the features and give some examples on how to use them.

Understanding the IsDirty flag

This flag indicates wether one of your model's properties has been changed after the last commit.
It is set to true whenever SetValue() is called and on the other hand set to false when calling
CommitChanges() or ResetChanges(). In addition, there is a ClearIsDirtyFlag() for cases when you need to reset IsDirty to false but can't use CommitChanges() or ResetChanges().

var model = new Model(); // IsDirty is false
model.Name = "Joe Example"; // IsDirty is true here

model.CommitChanges(); // IsDirty is false again

model.Phone = "1234567890"; // IsDirty is true
model.ResetChanges(); // IsDirty is true and Phone is string.Empty again

model.Id = 1234; // IsDirty is true
model.ClearIsDirtyFlag(); // IsDirty is false

LastPropertySet

This can be used to get the name of the property that was last changed.

var model = new Model(); // LastPropertySet is string.Empty
model.Name = "Joe Example"; // LastPropertySet is "Name"

model.CommitChanges(); // LastPropertySet is string.Empty

model.Phone = "123456789"; // LastPropertySet is "Phone"
model.ResetChanges(); // LastPropertySet is string.Empty

CommitChanges()

This method will copy all of your model's current property values into a private ConcurrentDictionary.
IsDirty and LastPropertySet are reset to its initial values.
A boolean indicating wether commiting was successful is returned from the method.

You can override this method to adapt it to your needs and extend its functionality.

ResetChanges()

This method is used for the exact opposite of CommitChanges().
It reads the values that are stored inside the private ConcurrentDictionary and writes them back at the according properties. If there are no values stored yet (no CommitChanges() call has been made), initial values are used.

You can override this method to adapt it to your needs and extend its functionality (e.g. reset fields aswell).

Clone this wiki locally