If I type a letter into a TextBox, and its content changes according to my keypress, why does the KeyDown event continue bubbling up? I would have thought this would be 'handled' at this stage.
Since KeyDown
event is a bubbling event
, that's why its bubbled to its parent in your case Window. If you don't want that to bubbled to your window, you need to mark it as handled in your textBox handler itself like this -
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
e.Handled = true;
}
Whereas, if you try to hook the event PreviewKeyDown
in your textBox, you will see that - Window's PreviewKeyDownEvent gets called first and later that of your textBox. Reason behind that is, it's a tunelling event
. For routing strategies, refer to this link - Routing Strategies
EDIT
Morevoer, if you want to check if the KeyDown event comes from textBox, you can check the OriginalSource
of your eventArgs -
private void Window_KeyDown(object sender, KeyEventArgs e)
{
// Check to make sure event comes from window and not from textbox.
if(e.OriginalSource is Window)
{
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With