简体   繁体   English

如果设置为true,AcceptsReturn会禁用多行文本框中Key.Return的检测?

[英]If set to true, AcceptsReturn disables detection of Key.Return in a multiline textbox?

In my Windows application, I made a multiline textbox by setting AcceptsReturn property to True. 在我的Windows应用程序中,我通过将AcceptsReturn属性设置为True来创建多行文本框。 It lets the user enter multiple lines of text into the textbox. 它允许用户在文本框中输入多行文本。 Also, I'd like to do something every time, the Return/Enter key is pressed in the textbox. 此外,我想每次都做一些事情,在文本框中按下Return / Enter键。 The event handler code is as follows... 事件处理程序代码如下......

private void TextBox_KeyDown(object sender, KeyEventArgs e)
{ 
    if (e.Key == Key.Return)

        // do something here
}

It appears that, if AcceptsReturn is set to True and the Return key is pressed, this event handler is not called at all. 看来,如果将AcceptsReturn设置为True并按下Return键,则根本不会调用此事件处理程序。 Any other key press is detected properly. 正确检测到任何其他按键。 If AcceptsReturn is not set to True and the Return key is pressed, the event handler is called and Return key press is detected just fine. 如果AcceptsReturn未设置为True并且按下Return键,则调用事件处理程序并检测返回键按下就好了。 The problem with this is that pressing Return key doesn't advance the user to the new line in the textbox (as expected). 这样做的问题是按下Return键不会使用户前进到文本框中的新行(如预期的那样)。 So, I'd like the Return key press to properly advance the user to the new line in the textbox as well as I'd like to be able to detect that Return key press. 所以,我希望按下返回键以正确地将用户推进到文本框中的新行,并且我希望能够检测到返回键按下。 Is my approach wrong? 我的方法有误吗? Is there a better way to do this? 有一个更好的方法吗?

KeyDown is bubbling event, which means it is first raised on the source control (the TextBox ), then on the parent, then on the parent's parent, and so on, until it is handled. KeyDown是冒泡事件,这意味着它首先在源控件( TextBox )上,然后在父TextBox上,然后在父父的父TextBox上,依此类推,直到它被处理。 When you set AcceptsReturn to true, the control handles the Return key, so the event is not bubbled. AcceptsReturn设置为true时,控件将处理Return键,因此事件不会冒泡。 In this case you can use the tunneling version of the event: PreviewKeyDown , which is raised on each ancestor of the control from the top to the bottom before it reaches the source control. 在这种情况下,您可以使用事件的隧道版本: PreviewKeyDown ,它在控件的每个祖先从顶部到底部到达源控件之前引发。

See Routing Strategies on MSDN 请参阅MSDN上的路由策略

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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