2

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?

icube
  • 2,578
  • 1
  • 30
  • 63
  • As I understand it, WPF implements most of its events using WeakEventManagers. Could you put up code showing how you normally wire up events? – Aron Sep 02 '13 at 04:09
  • like I mentioned in the post, I would use this method to listen to events even if they are handled: UIElement.AddHandler(RoutedEvent routedEvent, Delegate handler, bool handledEventsToo). I would like to know if can use the generic form of the WeakEventManager class for this – icube Sep 04 '13 at 06:56
  • As I understand the msdn page that introduces the Weak Event Managers, it would be slow than using a non generic manager. – Aron Sep 04 '13 at 10:43

1 Answers1

2

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);
torvin
  • 6,515
  • 1
  • 37
  • 52
nmclean
  • 7,564
  • 2
  • 28
  • 37