Using WeakEventManager with a static event

Is it possible to create a weak event listener for a static event using WeakEventManager?

I would like to create a weak event listener in the static CompositionTarget.Rendering event to avoid memory leaks when I don't know the lifetime of the WPF / Silverlight source element.

I implemented a rendering event manager using a weak event schema :

public class RenderingEventManager : WeakEventManager { public static void AddListener(IWeakEventListener listener) { CurrentManager.ProtectedAddListener(null, listener); } public static void RemoveListener(IWeakEventListener listener) { CurrentManager.ProtectedRemoveListener(null, listener); } private static RenderingEventManager CurrentManager { get { var managerType = typeof(RenderingEventManager); var manager = (RenderingEventManager)GetCurrentManager(managerType); if (manager == null) { manager = new RenderingEventManager(); SetCurrentManager(managerType, manager); } return manager; } } protected sealed override void StartListening(object source) { CompositionTarget.Rendering += this.OnCompositionTargetRendering; } protected sealed override void StopListening(object source) { CompositionTarget.Rendering -= this.OnCompositionTargetRendering; } void OnCompositionTargetRendering(object sender, EventArgs e) { this.DeliverEvent(sender, e); } } 

and checked the manager in a simple window:

 public partial class Window1 : Window, IWeakEventListener { public Window1() { InitializeComponent(); RenderingEventManager.AddListener(this); } bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e) { return true; } } 

The ReceiveWeakEvent method is not called. OnCompositionTargetRendering is called, but it looks like the DeliverEvent is not working as I expected. Adding listeners to instance events such as Button.Click works fine ... The test project is in the .NET 4.0 client profile.

A Microsoft Connect post from 2009 indicates that static events are not supported, but I checked the source code of WeakEventManager and it looks fine:

  protected void ProtectedAddListener(object source, IWeakEventListener listener) { Debug.Assert(listener != null, "Listener cannot be null"); object sourceKey = (source != null) ? source : StaticSource; ... } 
+7
source share
1 answer

Build yourself: change the sender argument of the DeliverEvent method to null:

 void OnCompositionTargetRendering(object sender, EventArgs e) { this.DeliverEvent(null, e); } 
+7
source

All Articles