When I do
WeakEventManager<SystemEvents, EventArgs>
.AddHandler(null, nameof(SystemEvents.DisplaySettingsChanged), OnDisplaySettingsChanged);
My OnDisplaySettingsChanged
never gets called. However, if I instead use normal event subscribtion via SystemEvents.DisplaySettingsChanged += OnDisplaySettingsChanged
everything works fine.
What's going on?
Turns out it's
WeakEventManager
's fault. When the event is fired, it implies thatsource
will benull
for static event sources (code excerpt from the reference source):But
sender
is nevernull
forSystemEvents
. Instead it passes a private instance ofSystemEvents
,WeakEventManager
then assumes it's another instance it didn't previously know about and doesn't call the handler.Here's the workaround I came up with:
Usage example:
Some explanation:
SystemEvents
holds a strong reference toEventProxy
, which holds a weak reference to the handler (viaWeakEventManager
)WeakEventManager
subscribes to the event insideAddHandler
, the proxy subscribes to the original eventEventProxy
acts as a proxy between the static event and the handler, invoking the handler whenever the original event firesWeakEventManager
will eventually run a cleanup, discover that the handler is dead and unsubscribe