He began to learn WPF from the book of MacDonald and was confronted with a misunderstanding of the practical purpose of routed events.

Can someone give a practical example when they are used? Is it true that these events are used only when writing their controls?

  • Still these events are present practically in all elements of UIElement, and not only in controls. Since they have a mechanism of surfacing and tunneling, it is necessary to understand the principle of their work. Otherwise, you can stumble upon a rather strange behavior of the program. The same features can be used when processing events in other places, a typical example, interception of hot keys. - Alex Krass

1 answer 1

A practical example: I was not satisfied with the usual scroll speed of the ScrollViewer and as a result, I increased the scrolling speed by 30 times:

 <ScrollViewer PreviewMouseWheel="ScrollViewer_OnPreviewMouseWheel"> 

And the handler:

 private void ScrollViewer_OnPreviewMouseWheel(object sender, MouseWheelEventArgs e) { var scrollViewer = sender as ScrollViewer; if (scrollViewer != null) { scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset + (30 * (e.Delta > 0 ? -1 : 1))); e.Handled = true; } } 

What happened (in simple terms): I intercepted the PreviewMouseWheel mouse-routed event before this event "failed" further (and would get directly to the ScrollViewer handler, which would perform scrolling at normal speed). Then I just manually scrolled the scroll (using ScrollToVerticalOffset ) by the amount of scrolling, increased by 30 times.

Since the scrolling on the fact has already been done, I do not need the event to "fail" further (which will cause the scrolling to be activated by default on the scroll side), so I use the capabilities of the routed event and prevent it from "fail" further by setting e.Handled = true .

Regarding the second question, I did not quite understand. You can use routed events of existing controls, as well as create arbitrary routed events for your controls.