Wpf – What are WPF Preview Events

eventswpf

I have been looking for descriptions of events "Preview******" like every element has events KeyDown and PreviewKeyDown. What is difference (not that one is attached event and one is not, the real conventional difference and programming way difference)

In any class derived from Control, you can override both methods.. OnKeyDown and OnPreviewKeyDown, now I am writing my custom control, which method shall I use? And whats difference between both of them.

Best Answer

From Programming WPF - Chris Sells and Ian Griffith

With the exception of direct events, WPF defines most routed events in pairs - one tunnelling and the other bubbling. The tunnelling event name always begins with 'Preview' and is raised first. This gives parents the chance to see the event before it reaches the child. This is followed by the bubbling counterpart. In most cases, you will handle only the bubbling one. The Preview would be usually used to

  • block the event (e.Handled = true)
  • cause the parent to do something in advance to normal event handling.

e.g. if UI Tree = Button contains Grid contains Canvas contains Ellipse
Clicking on the ellipse would result in (MouseDownButton is eaten up by Button and Click is raised instead.)

PreviewMouseDownButton
PreviewMouseDownGrid
PreviewMouseDownCanvas
PreviewMouseDownEllipse
MouseDownEllipse
MouseDownCanvas
MouseDownGrid