Stateless View Models

To minimize the number of degrees of freedom in an application, remove state from the view model. Store everything in the model and project it through the view model.

Structure

image

MVVM has three parts:

  • The Model
  • The View Model
  • The View

The model is responsible for storing application data. The view model interprets that data in a way that it can be displayed. And the view presents that data to the user.

Whereas a stateful view model keeps a copy of the data in the model, a stateless view model does not. This resolves the problem of keeping view models in sync. Since view models have no state, there is nothing to synchronize.

The model

The model contains all of the mutable properties. These are backed by fields.

public class Person
{
    private Independent<string> _name = new Independent<string>("Steve");

    public string Name
    {
        get { return _name.Value; }
        set { _name.Value = value; }
    }
}

The view model

No state in the view model means no fields and no auto-properties. Instead, all properties are get/set pairs of functions, except for read-only properties which are just get functions. The functions simply refer to properties of the model, which in accessed through a read-only field.

public class MainViewModel
{
    private readonly Person _person;

    public MainViewModel(Person person)
    {
        _person = person;
    }

    public string Name
    {
        get { return _person.Name; }
        set { _person.Name = value; }
    }
}

Computed properties

To compute a property, simply implement the computation in the view model’s property getter. If the user can set a computed property, write the inverse function in the setter.

    public string Greeting
    {
        get { return "Hello, " + _person.Name; }
    }

Dependency tracking

The traditional technique of raising property changed notifications in the "set" method does not work for stateless view models. The state could change because of a different view model, or a different property of the same view model. Model state can eve change in a different thread. So it is necessary to use a dependency tracking library like Update Controls to fire property changed events automatically. A dependency tracking framework will observe the model properties that a "set" method accesses. When one of those model properties changes, the library raises property changed for the view model property.