wpf C# - 如何覆盖文本框的“向上箭头”和“向下箭头”操作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16263854/
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
C# - How to override actions for "Up arrow" and "Down arrow" for a textbox?
提问by Kitze
I have a textbox and below it i have a listbox.
我有一个文本框,下面有一个列表框。
While the user is typing in the textbox if he presses the up or down arrow he should make a selection in the listbox. The textbox detects all the characters (except space) but it seems that it can't detect the arrow presses.
当用户在文本框中键入时,如果他按下向上或向下箭头,他应该在列表框中进行选择。文本框检测到所有字符(空格除外),但似乎无法检测到箭头按下。
Any solution for this? This is a WPF project btw.
有什么解决办法吗?顺便说一句,这是一个 WPF 项目。
EDIT, Here's the working code thanks to T.Kiley:
编辑,这是感谢 T.Kiley 的工作代码:
private void searchBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.IsDown && e.Key == Key.Down)
{
e.Handled = true;
//do your action here
}
if (e.IsDown && e.Key == Key.Up)
{
e.Handled = true;
//do another action here
}
}
采纳答案by Anthony Russell
I just tried this and it works. Add a preview key down event to the textbox
我刚试过这个,它的工作原理。向文本框添加预览键按下事件
private void TextBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.IsDown && e.Key == Key.Down)
MessageBox.Show("It works");
}
回答by T. Kiley
You can listen to they KeyDownevent of the TextBox. In the handler, check whether the arrow key was pressed (you might need to listen to key up to avoid triggering your code multiple times if the user holds down the button for too long).
你可以监听TextBox 的KeyDown事件。在处理程序中,检查是否按下了箭头键(如果用户按住按钮太久,您可能需要监听 key up 以避免多次触发您的代码)。
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Down)
{
// Do some code...
}
}

