Refactoring a PropertyChanged Event Handler

Just a quick code hit I’ve been meaning to blog about … I’ve seen a lot of examples that implement the  PropertyChanged event handler of the INotifyPropertyChanged interface. Most of them are demonstrating how to deal with data binding (including my examples) and most of them simply repeat the code that does the event raising. Some go as far as creating a method that does the raising, too.What I don’t like about the examples that extract a method that does the event raising is that each class would then need to have its own extracted method. Or you could (cringe) put it in a utility class.

Another solution is to create an extension method. But  sometimes the oldies are the best ways to do things. So here is an example I chose to use in a recent project. I had already created a base class for my entities and named it EntityBase.

I made the EntityBase implement the INotifyPropertyChanged interface and implemented its single event (PropertyChangedEventHandler) as a virtual event named PropertyChanged.

Then I created a method in the abstract base class named PropertyChangedHandler (the name is up to you) and its accepts an instance of EntityBase to be used as the sender and the name of the property that is changing.  (see the code below)

[DataContract]
public abstract class EntityBase : INotifyPropertyChanged    
{
    protected void PropertyChangedHandler(EntityBase sender, string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
    }
    public virtual event PropertyChangedEventHandler PropertyChanged;  
}

 

A class can inherit from the EntityBase (mine already did anyway) and override the event.

[DataContract]
public class Product : EntityBase
{
    public override event PropertyChangedEventHandler PropertyChanged;
...
...

 

Finally, here is an example of a property accessor that calls the base class’ protected method PropertyChanged.

[DataMember]
public string CategoryName
{
    get { return _categoryName; }
    set
    {
        _categoryName = value;
        base.PropertyChangedHandler(this, "CategoryName");
    }
}

 

The nice thing about this technique is that you just have a single line of code to execute the method in the base class that raises the notification. I wish I could have made the base class’ event abstract, but nothing is perfect.

You can omit the call to the base class in the code above, too. I just left in the word “base” to make it very clear in the example here.

If anyone else has any thoughts on better ways or just different ways to handle it, I am interested in hearing your thoughts.

Tweet Post Share Update RSS

Hi, I'm John Papa. I author this blog, create courses for Pluralsight and am a Google Developer Expert and Microsoft Regional Director. I travel speaking at events and train technology thought leaders

Tags:
All