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

Simplifying MVVM Properties

By , 29 Jun 2012
 

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;
            currentValue = newValue;
            RaisePropertyChanged(property.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
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberHarry von Borstel6 Sep '12 - 23:10 
GeneralRe: My vote of 5memberCollin Jasnoch7 Sep '12 - 3:35 
QuestionStackFramemembernoav3 Jul '12 - 3:01 
SuggestionSetProperty overloadmemberkosmoh1 Jul '12 - 19:52 
GeneralRe: SetProperty overloadmemberCollin Jasnoch2 Jul '12 - 2:42 
SuggestionRe: SetProperty overloadmemberHarry von Borstel6 Sep '12 - 22:58 

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 29 Jun 2012
Article Copyright 2012 by Collin Jasnoch
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid