Click here to Skip to main content
Click here to Skip to main content

Simplifying MVVM Properties

By , 30 Sep 2013
Rate this:
Please Sign up or sign in to vote.

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:

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

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:
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.
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:
[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)

About the Author

Collin Jasnoch
Engineer
United States United States
No Biography provided

Comments and Discussions

 
QuestionI don't understand exactly... PinmemberGyuwon Yi9-Oct-13 15:47 
AnswerRe: I don't understand exactly... PinprofessionalCollin Jasnoch10-Oct-13 1:58 
GeneralRe: I don't understand exactly... PinmemberGyuwon Yi10-Oct-13 2:28 
SuggestionRe: I don't understand exactly... PinprofessionalRichard Deeming10-Oct-13 9:15 
GeneralRe: I don't understand exactly... PinprofessionalCollin Jasnoch10-Oct-13 9:26 
GeneralMy vote of 5 PinmemberHarry von Borstel6-Sep-12 23:10 
GeneralRe: My vote of 5 PinmemberCollin Jasnoch7-Sep-12 3:35 
QuestionStackFrame Pinmembernoav3-Jul-12 3:01 
AnswerRe: StackFrame PinprotectorPete O'Hanlon30-Sep-13 10:10 
GeneralRe: StackFrame Pinmembernoav4-Nov-13 21:33 
SuggestionSetProperty overload Pinmemberkosmoh1-Jul-12 19:52 
GeneralRe: SetProperty overload PinmemberCollin Jasnoch2-Jul-12 2:42 
SuggestionRe: SetProperty overload PinmemberHarry von Borstel6-Sep-12 22:58 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140415.2 | Last Updated 30 Sep 2013
Article Copyright 2012 by Collin Jasnoch
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid