I have the class which implements INotifyPropertyChanged
and therefore I have the event:
public event PropertyChangedEventHandler PropertyChanged
There are a lot of places (more than 300) in the solution where event listeners subscribe to the PropertyChanged
event using the standard operator +=
. I want to change the way of subscription to using WeakEventManager
to decrease the risks of memory leaks. And of course I wouldn't like to change all more than 300 places in the code. Here is what I was able to come up with but it doesn't work:
public event PropertyChangedEventHandler PropertyChanged
{
add
{
WeakEventManager<BaseNotifyPropertyChanged, EventArgs>.AddHandler(this, "PropertyChanged", (EventHandler<EventArgs>)value);
//or
PropertyChangedEventManager.AddHandler(this, value, "IsDirty");
}
remove
{
//....
}
}
But it is impossible to cast type PropertyChangedEventHandler
to EventHandler<EventArgs>
.
How can I resolve the problem?
UPD:
To resolve the issue above I used anonymous method:
WeakEventManager<BaseNotifyPropertyChanged, EventArgs>.AddHandler(this,
"PropertyChanged",
(sender, e) => value(sender, (PropertyChangedEventArgs)e));
Thanks PeterDuniho for advise.
But now if I try raise the event:
protected virtual void RaiseOnPropertyChangedEvent(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
I got the next error:
The event PropertyChanged can only appear on the left hand side of +=
or -=
This error is quite known, but in another context. What is the reason?