如何阻止 WPF KeyDown 事件从某些包含的控件(例如 TextBox)冒泡?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24872940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I stop WPF KeyDown events from bubbling up from certain contained controls (such as TextBox)?
提问by redroze
My program is quite large, and uses WPF, and I want to have a global shortcut key that uses 'R', with no modifiers.
There are many controls such as TextBox, ListBox, ComboBox, etc. that all use letters inside the control itself, which is fine - that's correct for me.
But - I want to keep that KeyDown event from bubbling up to the main window, where it would trigger the shortcut any time a user is typing the letter 'R' in a TextBox, for example.
Ideally, I would like to be able to do this without having to specify (and do if-then logic on) every instance/type of control that might receive normal alphabetical key presses (not just the TextBox controls, though they are the worst offenders).
我的程序非常大,并且使用 WPF,我想要一个使用“R”的全局快捷键,没有修饰符。
有很多控件,例如 TextBox、ListBox、ComboBox 等,它们都在控件本身内部使用字母,这很好 - 这对我来说是正确的。
但是 -我想防止 KeyDown 事件冒泡到主窗口,例如,只要用户在 TextBox 中键入字母“R”,它就会触发快捷方式。
理想情况下,我希望能够做到这一点,而不必指定(并执行 if-then 逻辑)可能接收正常字母按键按下的每个实例/控件类型(不仅仅是 TextBox 控件,尽管它们是最严重的违规者) )。
回答by Troels Larsen
Simply check what the OriginalSourceis in your KeyDownevent handler on the Window:
只需按一下什么OriginalSource是你的KeyDown窗口事件处理程序:
private void Window_KeyDown(object sender, KeyEventArgs e) {
if(e.OriginalSource is TextBox || e.OriginalSource is DateTimePicker) //etc
{
e.Handled = true;
return;
}
}
Or if you are using InputBindings, experiment with setting e.Handled = truein either the KeyDownor the PreviewKeyDownevent on your Window, rather than the individual controls. In anyway, I think OriginalSourceis the key to your answer. (I swear that was not a pun).
或者,如果您正在使用 InputBindings,请尝试e.Handled = true在Window 上的KeyDown或PreviewKeyDown事件中进行设置,而不是在单个控件中进行设置。无论如何,我认为OriginalSource是你回答的关键。(我发誓这不是双关语)。
回答by 123 456 789 0
There is an event when you handle KeyDownevent and it should pass you a KeyEventArgs. From there you can set the Handledto trueso that it won't bubble up.
当您处理事件时有一个事件KeyDown,它应该传递给您一个KeyEventArgs. 从那里你可以将 设置Handled为true ,这样它就不会冒泡。
Sample
样本
private void TextBoxEx_KeyAction(object sender, KeyEventArgs e)
{
e.Handled = true;
}

