简体   繁体   中英

How does WPF TextBox “knows” that a KeyDown event was handled

I noticed that when a window is handling the KeyDown event raised by a text box in it and set the event Handled flag to true, the text box ignores the pressed key and doesn't add it to its content.

According to my understanding of how things work, the PreviewKeyDown event if first tunneling from the window to the TextBox and then the KeyDown event is bubbling up from the TextBox to the window. By the time the window's event handler gets to set the Handled event, the event is no longer handled by the TextBox, but I do see that it has an effect, and pressed keys are not added to the TextBox.

Can someone explain how this works?

(this is a general question, but was raised after I saw a similar behavior in a third-party control we are using, and it caused me problems, as I wanted the control to handle the event but stop it from bubbling upwards.)

Well, IN reality, those events will ALWAYs bubble/tunnel, no matter if it's handled or not. It's just the case that most of event handlers are not registered to recieve "handled" events.

For an example, there is option to subscribe against KeyDown event and recieve the "call" even if it's handled somewhere up.

But yes, the order of events are usually that it starts from top(tunneling), then tunnels back down to element and bubbles up.

If you have more questions, let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM