using WPF 4.5 Generic Weak Event Manager for Handled Routed Events?

2.6k views Asked by At

I would like to know how to convert the subscription of "Handled" RoutedEvents to WeakEventManager?

UIElement has the following method to subscribe to "Handled" RoutedEvents: UIElement.AddHandler(RoutedEvent routedEvent, Delegate handler, bool handledEventsToo)

So how do I convert it the the Generic WeakEventManager form?

1

There are 1 answers

3
nmclean On

You should be able to just follow the guide for creating a custom event manager from MSDN, and implement StartListening and StopListening like this:

protected override void StartListening(object source) {
    var sourceElement = (UIElement)source;
    sourceElement.AddHandler(RoutedEvent, OnRoutedEvent, true);
}

protected override void StopListening(object source) {
    var sourceElement = (UIElement)source;
    sourceElement.RemoveHandler(RoutedEvent, OnRoutedEvent, true);
}

I don't think it would make much sense to use the generic WeakEventManager for this, because it uses an event name and calls Type.GetEvent internally, which isn't useful at all when you're using RoutedEvents and AddHandler instead of "real" events. However, you may be able to write your own generic base class for working with RoutedEvents.


Personally, I use my own weak event solution based on Dustin Campbell's WeakEventHandler. The nice thing about it is that instead of managing adding and removing internally, it gives you a "weak" version of the original delegate which you can pass around freely... so there is no need to customize the weak event manager's implementation when adding delegates in a different way, because the usage is the same in both cases:

uielement.MouseDown += weakMouseDownHandler;

uielement.AddHandler(UIElement.MouseDownEvent, weakMouseDownHandler, true);