0

I'm reading the MS docs on how to implement the weak event pattern. I've tried the first two (since I'm looking for the simplest way) but I can't find a way to raise the event.

The existing weak event managers like the PropertyChangedEventManager, and the generic WeakEventManager only have methods to add and remove handlers but nothing to raise the event. Also, I can't inherit those it says [the base class] does not contain a constructor that takes 0 arguments (the constructors are private).

So I'm finding the docs confusing - how are these constituted the ways to implement the weak event pattern if there's no way to raise the event?

If the suggested way in the docs doesn't work I'm looking for the simplest way to raise and handle weak events.

Hossein Ebrahimi
  • 632
  • 10
  • 20
  • 1
    The events are normal events. The event source is not affected by the weak event pattern. The pattern allows the observer to handle events without establishing a strong reference from the event source to the event handler. It's this strong reference that allows the event source to invoke the registered delegate, but also extends the lifetime of the observer and therefore creates a potential memory leak. Registering an event handler by following the pattern creates a weak reference instead. The lifetime of the observer is now independent of the event source. Events are raised as usual. – BionicCode Jan 13 '23 at 21:49
  • @BionicCode YES! that's the answer – Hossein Ebrahimi Jan 13 '23 at 21:58
  • 1
    The easy ways to implement this are bindings or https://learn.microsoft.com/en-us/dotnet/api/microsoft.toolkit.mvvm.messaging.weakreferencemessenger?view=win-comm-toolkit-dotnet-7.1 – Andy Jan 13 '23 at 22:00
  • Did you have something specific in mind? There are routed events and inherited dependency properties don't rely on hard references. – Andy Jan 13 '23 at 22:07
  • @Andy The WeakReferenceMessanger looks nice, I may give it a try. The event is going to communicate among some view-models but somewhere that doesn't get cleared without unregistering manually, so I'm not using bindings – Hossein Ebrahimi Jan 13 '23 at 22:10
  • Messenger is really useful. I recommend that mvvm toolkit generally. – Andy Jan 13 '23 at 22:26

0 Answers0