WPF MVVM – Model Change Tracking

By | June 23, 2013
I found the change tracking in WPF always a little bit painful, when working with simple POCOs without any change tracking context (for example ADO.NET EF). Therefore, I wrote a small library which simplifies the tracking.

The Lib contains three interesting classes:

EditableObject: Imlements the IEditableObject interfaces and handles the revert functionality and change tracking. Every model has to inherit from this class.
EditableCollection: Inherits from ObservableCollection and contains a generic type restriction which allows only types implementing the interface IEditTracking. This collection handles the added/deleted events.
UntrackedContext: Disable the tracking in a specified flow. Can be used for EditableObject and EditableCollection.

In short: When you are editing a model in a single form, then all functions you need are implemented in the EditableObject class. When you are editing models in a grid, then you have to handle the Added/Removed events. This works takes the EditableCollection over.

Goodies:
The revert functionality in the EditableObject class uses the EmitMapper. When reverting the previous state of the model, the object reference will be retained! It just reverts the property values without de/serializing the whole object.

Here is an extract from the demo app. (The GitHub link is at the bottom of this post.)


public class PersonModel : EditableObject<PersonModel>
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

this.People = new EditableCollection<PersonModel>();
using (UntrackedContext<EditableCollection<PersonModel>>.Untrack(this.People))
{
	this.People.Add(new PersonModel() { Firstname = "Darko", Lastname = "Micic" });
        this.People.Add(new PersonModel() { Firstname = "Max", Lastname = "Muster" });
}

I’ll use this Lib in my next project. It could be that this version contains some bugs, because it’s untested.
Here is the link: https://github.com/dmicic/MvvmModelChangeTracking