Safe usage of INotifyPropertyChanged in MVVM scenarios

For my first post in this blog I’m going to describe how we can use the INotifyPropertyChanged without magic strings in MVVM scenarios by using lambda expressions. If you’re not familiar with this pattern you can read about it here:

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

When using MVVM we usually tend to create a base class that contains the INotifyPropertyChanged implementation as following:

public abstract class ViewModelBase : INotifyPropertyChanged
{
    protected void RaisePropertyChanged(string property)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(property));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

A simple ViewModel class could look like this:
public class SampleVM : ViewModelBase
{
    private string _sampleProperty;
    public string SampleProperty
    {
        get { return this._sampleProperty; }
        set
        {
            this._sampleProperty = value;
            base.RaisePropertyChanged("SampleProperty");

            this.IsEnabled = this._sampleProperty != null;
            base.RaisePropertyChanged("IsEnabled");
        }
    }

    public bool IsEnabled { get; private set; }
}

I’ve used this approach a lot and it works great but it has some problems.

Continue reading

Advertisements