Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WPF

Simplifying MVVM Properties

5.00/5 (2 votes)
30 Sep 2013CPOL2 min read 39.7K  
Simplify your MVVM Properties

Introduction

In .NET 4.5 Microsoft has created a CallerMemberName attribute to simplify the INotifyPropertyChange. However they also refactored out a lot of the handling of the traditional MVVM properties. With this little snippet in your View Model Base you will be able to mimic such behavior. The catch is that you will be using some reflection.

Background

The traditional View Model Base is as follows:

C#
public class ViewModelBase : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Doing this however creates a pain when refactoring and renaming as your adjusted properties will not carry through. For example you have decided to make your ID to be more clear by calling it CustomerID. Adjusting the property name will of course break it for multiple reasons the first being you are posting the INotifyPropertyChanged as ID so you will need to adjust the string in the code as well as the XAML. Now I do not have a trick for helping with the XAML but using reflection we can get the code to adjust for you with the Visual Studio Rename feature. In addition we will refactor the checking of the variable and setting of it using the code with in .Net 4.5.

Using the code

C#
public class ViewModelBase : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;

    protected bool SetProperty<t>(ref T fieldReference, T newValue, Expression<func<t>> property)
    {
        bool valueIsDifferent = false;
        if(!object.Equals(fieldReference, newValue))
        {
            valueIsDifferent = true;
            fieldReference = newValue;

            var memberExpression = property.Body as MemberExpression;
            RaisePropertyChanged(memberExpression.Member.Name);
        }
    }

    protected void RaisePropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
Now you can easily set up all your MVVM properties to be much simpler:
C#
private int _someFieldValue;

///

public int SomePropertyValue
{
    get { return _someFieldValue; }
    set { SetProperty(ref _someFieldValue, value, () => SomePropertyValue); }
}
Then in the case where you do have custom logic you must run upon value change you just take advantage of the return.
C#
private int _someFieldValue;

///

public int SomePropertyValue
{
    get { return _someFieldValue; }
    set 
    { 
            if(SetProperty(ref _someFieldValue, value, () => SomePropertyValue))
            {
                //Custom Logic that runs when the value changes
            }
    }
}

Points of Interest

It always bugged me that I had to write the same gobldy gook over and over for MVVM compliant properties. This at least simplifies that. .NET 4.5 does not require you to pass the property even and also it happens at compile time rather than run time so there is a definite advantage to using it if you can. Until then enjoy this simplification. I do wish that in .NET 4.5 it was as simple as this though:
C#
[PostToINotify(true)]
public int SomePropertyValue {get; set;}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)