Quantcast
Viewing all articles
Browse latest Browse all 8

WPF, MVVM and RaisePropertyChanged

Several times recently during development I have come across situations where specific strings are required for functionality to work effectively and yet not having the correct string will not cause any compilation or run time errors, features just won’t work. The features may be subtle enough such that it could be some time before any break in functionality is noticed and therefore could reach production code. In coding terms these are called “magic strings” and are something to be avoided at all costs.

One example of this I have come across often in MVVM WPF or Silverlight projects where the ViewModels implement the INotifyPropertyChanged interface such that when a property is changed it is common to see code such as the following.

private string _firstName;
public string FirstName
{
    get { return _firstName; }
    set
    {
        if (_firstName != value)
        {
            _firstName = value;
            RaisePropertyChanged("FirstName");
        }
    }
}

The alarm bell for me here is the hard coded name of the property “FirstName” within the RaisePropertyChanged method. In this simple example it is clear, but in more complex code it can easily get lost and also magic strings such as these won’t be picked up and adjusted in any automated refactoring of the names of the properties.

You can obtain the name of the property using the following bit of code, however it includes either ‘get_’ or ‘set_’ at the start depending upon where it is called.

MethodBase.GetCurrentMethod().Name;

Thus I’ve created the following extension method to take the property name and simply strim off the first 4 characters thus leaving you with the correct property name.

public static string GetPropertyName(this MethodBase methodBase)
{
    return methodBase.Name.Substring(4);
}

Using this extension method, as below, it means that you will be able to raise property changed events without concern that in future your property name might change.

RaisePropertyChanged(MethodBase.GetCurrentMethod().GetPropertyName());

Update: I’ve now created a Visual Studio code snippet that is used for creating field backed properties that automatically includes the “RaisePropertyChanged” call which can be found here.


Filed under: C#, MVVM, WPF Tagged: INotifyPropertyChanged, MVVM, RaisePropertyChanged, WPF Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 8

Trending Articles