A Microsoft platform for building and publishing apps for Windows devices.
PreviewKeyDown and PreviewKeyUp intentionally form a pre-processing phase that tunnels from the root to the focused element before keyboard accelerators, control handling, and the corresponding bubbling event run.
Documented routing sequence
For a key press, WinUI processes the relevant stages in this order:
-
PreviewKeyDowntunnels from the root toward the focused element. - Keyboard accelerators and the focused control get an opportunity to process the key.
-
KeyDownbubbles from the focused element toward the root, unless the input has already been handled. - Character input can follow for text controls.
The PreviewKeyDown API explicitly specifies the tunneling strategy and identifies KeyDown as its corresponding bubbling event.^1^ The keyboard-accelerator documentation also places preview events before accelerators, control OnKeyDown processing, bubbling KeyDown, and character input.^2^
Therefore, the sequence in the question is expected:
RootGrid PreviewKeyDown
Panel PreviewKeyDown
Input PreviewKeyDown
Input KeyDown
Panel KeyDown
RootGrid KeyDown
Purpose of the preview phase
The practical distinction is who gets first refusal:
- Use
PreviewKeyDownwhen a container must inspect or intercept a key before the focused child or its keyboard accelerator processes it. - Use
KeyDownwhen the focused control should process the key first and ancestors should react only if it remains unhandled.
For example, a root-level preview handler can reserve a key before the focused TextBox processes it:
void MainPage::Root_PreviewKeyDown(
IInspectable const&,
Microsoft::UI::Xaml::Input::KeyRoutedEventArgs const& args)
{
if (args.Key() == Windows::System::VirtualKey::Escape)
{
CloseCurrentOverlay();
args.Handled(true);
}
}
Set Handled only when the ancestor genuinely owns the operation. Otherwise, leave it false so focused-control behavior, accelerators, and KeyDown processing can continue. Controls can also handle keyboard input internally; in that case, an ordinary ancestor KeyDown handler might not run.^3^
Why only these preview events?
The WinUI documentation establishes that PreviewKeyDown/PreviewKeyUp are special tunneling keyboard events, but it does not document an architectural rationale for why WinUI exposes tunneling counterparts only for these events rather than for every routed event.
It is therefore safest to treat this as part of WinUI’s defined keyboard-input contract, not as a general rule that an event name beginning with Preview automatically tunnels or that every bubbling event has a preview counterpart. Other routed events use the strategy specified by their individual API contract; KeyDown and KeyUp, for example, use bubbling.^3^
References