Is there a way to write the canonical OnPropertyChanged method as an extension method?

Basically I want to do something like this:

public static void OnPropertyChanged(this INotifyPropertyChanged changedObject, string propertyName)
{
    var handler = changedObject.PropertyChanged;
    if (handler != null)
    {
        var e = new PropertyChangedEventArgs(propertyName);
        handler(changedObject, e);
    }
}

      

which gives "System.ComponentModel.INotifyPropertyChanged.PropertyChanged can only be used on the left side + = or - ="

I mean I can get around this by doing this:

public static void RaisePropertyChanged(this PropertyChangedEventHandler handler, object sender, string propertyName)
{
    if (handler != null)
    {
        var e = new PropertyChangedEventArgs(propertyName);
        handler(sender, e);
    }
}

      

but the calling code doesn't look so good:

PropertyChanged.RaisePropertyChanged(this, "Name");

      

vs this:

this.OnPropertyChanged("Name");

      

It doesn't matter, but it would be nice to call it as if it were an instance method.

0


a source to share


1 answer


This is also against the recommendation: On * methods in general are meant to do something based on something that is REALLY an injecting instance. In general, these methods are virtual, so you can override them in derived classes. Therefore, the On * method outwardly makes no sense. If you want to raise an event without the dreaded null test all over the place, you should really use the RaiseEvent () extension method. I've written a lot of them, all of which have overloads, so you can just use RaiseEvent (...) and you don't need to include the event name in this method. This is especially useful when, for example, you are using the regular EventHandler type, so you can use the same extension method for more events.



+1


a source







All Articles