Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

wpf

In my Windows application, I made a multiline textbox by setting AcceptsReturn property to 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. 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. 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. The problem with this is that pressing Return key doesn't advance the user to the new line in the textbox (as expected). 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?

like image 752
Erin Gibbs Avatar asked Dec 21 '22 15:12

Erin Gibbs


1 Answers

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. When you set AcceptsReturn to true, the control handles the Return key, so the event is not bubbled. 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.

See Routing Strategies on MSDN

like image 73
Thomas Levesque Avatar answered May 18 '23 20:05

Thomas Levesque