Monday, March 14, 2011

Some cool patterns for MVVM property initialization

This post is about how to setup properties commonly used in MVVM.

The ObservableCollection
I like to create a backing field property. Initilize the backing field immediately. Return the backing field in get. And clear then copy the items into the backing field in set. The performance of add might not be perfect but it is the only option I have I believe:


private ObservableCollection _OpenDocuments = new ObservableCollection();
public ObservableCollection OpenDocuments
{
    get { return _OpenDocuments; }
    set
    {
        _OpenDocuments.Clear();                
        foreach (var item in value)
        {
            _OpenDocuments.Add(item);
        }
    }
}


The RelayCommand
I got this pattern of the code from Karl : http://karlshifflett.wordpress.com/. Based on how he initializes his RelayCommand. Have a backing field. And in get check the backing field for null. If null create it. Finally return it.
Sample:

public RelayCommand _SaveStudent;
public RelayCommand SaveStudent
{
    get
    {
        if (_SaveStudent == null)
        {
            _SaveStudent = new RelayCommand(() => { Save(); }, () => { return CanSaveExecute(); });
        }
        return _SaveStudent;
    }

}



Enjoy!