What is the difference between a class listener and an instance listener in WPF?

I am trying to wrap my head around some things specific to WPF and have not yet found a specific relationship between the UIElement.AddHandler method and the EventManager.RegisterClassHandler method.

I googled a bit and found this interesting article on MSDN:

http://msdn.microsoft.com/en-us/library/ms747183.aspx

It says here:

โ€œForwarded events take into account two different types of event listeners: class listeners and instance listeners. Class listeners exist because the types called the specific EventManager API, RegisterClassHandler, in their static constructor or redefined the virtual class handler method from the element base, instance listeners are special instances / elements of the class in which one or more handlers were attached for this routed event by calling AddHandler. "

Ok, now I know the difference between a class and its instance, but somehow I can not figure out this specific part of the document.

Can someone clarify this for me?

+8
c # wpf routed-events
source share
1 answer

I donโ€™t know what exactly you want to know. Quite simple: you can register a handler at the instance (object) level or at the class level.

The difference is that when you register an event at the class level, it will be called first before all instance-level handlers (of course, tunneling or bubbling still occurs if the processing class is lower / higher in the logical tree). Thus, you can handle this event at the class level and filter whether this event should be handled by the instance or not (by setting e.Handled = true you will stop the event to pass through other handlers). This may be useful in some cases, but at the moment I have no example to share.

In this example, an event handler will be registered, which will be called only when the event was created for a specific instance of the element:

 DockPanel panel = new DockPanel(); panel.AddHandler(Button.ClickEvent, new RoutedEventHandler(Button_Click)); 

And this will create an event handler that will be called every time any DockPanel receives a Button.Click event before the instance handler of this DockPanel is called:

 EventManager.RegisterClassHandler(typeof(DockPanel), Button.ClickEvent, new RoutedEventHandler(ButtonClass_Click)); 

If there were the following methods:

 private void ButtonClass_Click(object sender, RoutedEventArgs e) { Debug.Write("Class level handler"); } private void Button_Click(object sender, RoutedEventArgs e) { Debug.Write("Instance level handler"); } 

This will produce the output:

Class level handler
Instance level handler

But if you specify args handeled arguments ( e.Handled = true; ) in the level handler, it will filter this event for the level handler (and bubble in the logical tree).

+11
source share

All Articles