1

I am currently using WPF and implementing a model related class deriving INotifyPropertyChanged. I have found that declaring some helper methods is very useful. So I wanted to add these helper methods automatically:

public static class INotifyPropertyChangedHelper
{
    static void notifyPropertyChanged(this INotifyPropertyChanged propertyChanged, string PropertyName = "")
    {
        // errors here
        propertyChanged.PropertyChanged(propertyChanged, new PropertyChangedEventArgs(PropertyName));
    }
    static bool setField<T>(this INotifyPropertyChanged propertyChanged, ref T field, T value, [CallerMemberName]string propertyName = "")
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        propertyChanged.notifyPropertyChanged(propertyName);
        return true;
    }
}

Gives me a compiler error

The event 'System.ComponentModel.INotifyPropertyChanged.PropertyChanged' can only appear on the left hand side of += or -=" because PropertyChanged is an event.

Is there an elegant way to solve this problem?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Laie
  • 540
  • 5
  • 14

1 Answers1

0

No easy trick to do this, extension methods are static methods recognized by compiler which do not become part of class itself. As += and -= on event are accessible only form class defining the event, extension method can't help you there.

I guess you are trying to hack one of the known problems: Implementing INotifyPropertyChanged - does a better way exist?

Community
  • 1
  • 1
watbywbarif
  • 6,487
  • 8
  • 50
  • 64