c# - Why can't I invoke PropertyChanged event from an Extension Method? -
i've tried code class avoid method "raisepropertychanged". know can inherit class has implementation in cases can't. i've tried extension method visual studio complain.
public static class extension { public static void raisepropertychanged(this inotifypropertychanged predicate, string propertyname) { if (predicate.propertychanged != null) { predicate.propertychanged(propertyname, new propertychangedeventargs(propertyname)); } } }
it said:
"the event 'system.componentmodel.inotifypropertychanged.propertychanged' can appear on left hand side of += or -="
reed right. however, see you're trying (make code reusable—good you); , i'll point out rectified accepting propertychangedeventhandler
delegate , passing within inotifypropertychanged
implementation:
public static void raise(this propertychangedeventhandler handler, object sender, string propertyname) { if (handler != null) { handler(sender, new propertychangedeventargs(propertyname)); } }
then within class implements inotifypropertychanged
, can call extension method so:
propertychanged.raise(this, "myproperty");
this works because, as marc said, within class declaring event can access field (which means can pass delegate argument method, including extension methods).
Comments
Post a Comment