Tuesday, 28 October 2014

INotifyPropertyChanged

The INotifyPropertyChanged interface is used to implement the observable pattern, that is one to many UI Elements can observe the value of a property, and if that property us changed it can updated the values of everything that's observing it.

here's the generic base class I use to implement it

public abstract class BaseModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected bool SetProperty<T>(ref T BackingField, T Value, [CallerMemberName] string PropertyName = "")
    {
        if (object.Equals(BackingField, Value))
            return false;
        BackingField = Value;

        this.UpdateProperty(PropertyName);

        return true;
    }

    protected void UpdateProperty([CallerMemberName] string PropertyName = "")
    {
        if (PropertyChanged != null && !String.IsNullOrEmpty(PropertyName))
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(PropertyName));
    }
}

it makes life a lot easier rather then setting it up on all your models, just make it once and inherit it where needed.