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 thatsourcewill benullfor static event sources (code excerpt from the reference source):But
senderis nevernullforSystemEvents. Instead it passes a private instance ofSystemEvents,WeakEventManagerthen 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:
SystemEventsholds a strong reference toEventProxy, which holds a weak reference to the handler (viaWeakEventManager)WeakEventManagersubscribes to the event insideAddHandler, the proxy subscribes to the original eventEventProxyacts as a proxy between the static event and the handler, invoking the handler whenever the original event firesWeakEventManagerwill eventually run a cleanup, discover that the handler is dead and unsubscribe