Click here to Skip to main content
12,503,947 members (55,032 online)
Click here to Skip to main content
Add your own
alternative version

Stats

20.4K views
17 bookmarked
Posted

Simplifying MVVM Properties

, 30 Sep 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

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)

Share

About the Author

N_tro_P
Engineer
United States United States
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionI don't understand exactly... Pin
Gyuwon Yi9-Oct-13 15:47
memberGyuwon Yi9-Oct-13 15:47 
AnswerRe: I don't understand exactly... Pin
Collin Jasnoch10-Oct-13 1:58
professionalCollin Jasnoch10-Oct-13 1:58 
GeneralRe: I don't understand exactly... Pin
Gyuwon Yi10-Oct-13 2:28
memberGyuwon Yi10-Oct-13 2:28 
SuggestionRe: I don't understand exactly... Pin
Richard Deeming10-Oct-13 9:15
professionalRichard Deeming10-Oct-13 9:15 
GeneralRe: I don't understand exactly... Pin
Collin Jasnoch10-Oct-13 9:26
professionalCollin Jasnoch10-Oct-13 9:26 
GeneralMy vote of 5 Pin
Harry von Borstel6-Sep-12 23:10
memberHarry von Borstel6-Sep-12 23:10 
GeneralRe: My vote of 5 Pin
Collin Jasnoch7-Sep-12 3:35
memberCollin Jasnoch7-Sep-12 3:35 
QuestionStackFrame Pin
noav3-Jul-12 3:01
membernoav3-Jul-12 3:01 
AnswerRe: StackFrame Pin
Pete O'Hanlon30-Sep-13 10:10
protectorPete O'Hanlon30-Sep-13 10:10 
GeneralRe: StackFrame Pin
noav4-Nov-13 21:33
membernoav4-Nov-13 21:33 
SuggestionSetProperty overload Pin
kosmoh1-Jul-12 19:52
memberkosmoh1-Jul-12 19:52 
GeneralRe: SetProperty overload Pin
Collin Jasnoch2-Jul-12 2:42
memberCollin Jasnoch2-Jul-12 2:42 
SuggestionRe: SetProperty overload Pin
Harry von Borstel6-Sep-12 22:58
memberHarry von Borstel6-Sep-12 22:58 
GeneralRe: SetProperty overload Pin
Xaotiq31-Mar-15 7:03
professionalXaotiq31-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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160919.1 | Last Updated 30 Sep 2013
Article Copyright 2012 by N_tro_P
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid