Handling the PropertyChanged event

When handling the PropertyChanged event of an object that implements INotifyPropertyChanged, one is tempted to write a handler like this:

    void Source_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "Text")
            UpdateText();
        else if (e.PropertyName == "Icon")
            UpdateIcon();
    }

Strictly speaking, this isn’t entirely correct. According to the documentation for the PropertyChanged event, “the PropertyChanged event can indicate all properties on the object have changed by using either null or string.Empty as the property name in the PropertyChangedEventArgs.” So, you’re forced to write something like this:

    void Source_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        bool bAllChanged = string.IsNullOrEmpty(e.PropertyName);
        if (bAllChanged || e.PropertyName == "Text")
            UpdateText();
        if (bAllChanged || e.PropertyName == "Icon")
            UpdateIcon();
    }

To make checking for this situation a little bit easier, and to increase the likelihood that we remember to do it, we put together a nice little extension method on PropertyChangedEventArgs called HasChanged:

    public static bool HasChanged(this PropertyChangedEventArgs e,
        string strPropertyName)
    {
        string strEventPropertyName = e.PropertyName;
        return string.IsNullOrEmpty(strEventPropertyName) ||
            strPropertyName == strEventPropertyName;
    }

Now, proper handling of the PropertyChanged event is as easy as this:

    void Source_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.HasChanged("Text"))
            UpdateText();
        if (e.HasChanged("Icon"))
            UpdateIcon();
    }

Just remember not to use “else”…

Posted by Ed Ball on April 01, 2008