Click here to Skip to main content
15,881,938 members
Articles / Desktop Programming / WPF
Tip/Trick

Simplifying MVVM Properties

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
30 Sep 2013CPOL2 min read 38.1K   17   14
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)



Comments and Discussions

 
QuestionI don't understand exactly... Pin
Gyuwon Yi9-Oct-13 15:47
Gyuwon Yi9-Oct-13 15:47 
AnswerMessage Removed Pin
10-Oct-13 1:58
professionalN_tro_P10-Oct-13 1:58 
GeneralRe: I don't understand exactly... Pin
Gyuwon Yi10-Oct-13 2:28
Gyuwon Yi10-Oct-13 2:28 
SuggestionRe: I don't understand exactly... Pin
Richard Deeming10-Oct-13 9:15
mveRichard Deeming10-Oct-13 9:15 
GeneralMessage Removed Pin
10-Oct-13 9:26
professionalN_tro_P10-Oct-13 9:26 
GeneralMy vote of 5 Pin
Harry von Borstel6-Sep-12 23:10
Harry von Borstel6-Sep-12 23:10 
GeneralMessage Removed Pin
7-Sep-12 3:35
professionalN_tro_P7-Sep-12 3:35 
QuestionStackFrame Pin
noav3-Jul-12 3:01
noav3-Jul-12 3:01 
AnswerRe: StackFrame Pin
Pete O'Hanlon30-Sep-13 10:10
mvePete O'Hanlon30-Sep-13 10:10 
GeneralRe: StackFrame Pin
noav4-Nov-13 21:33
noav4-Nov-13 21:33 
SuggestionSetProperty overload Pin
kosmoh1-Jul-12 19:52
kosmoh1-Jul-12 19:52 
GeneralMessage Removed Pin
2-Jul-12 2:42
professionalN_tro_P2-Jul-12 2:42 
SuggestionRe: SetProperty overload Pin
Harry von Borstel6-Sep-12 22:58
Harry von Borstel6-Sep-12 22:58 
GeneralMessage Removed Pin
31-Mar-15 7:03
professionalN_tro_P31-Mar-15 7:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.