If set to true, AcceptsReturn disables Key.Return detection in a multiline text field?

In my Windows application, I created a multi-line text box by setting the AcceptsReturn property to True. It allows the user to enter multiple text boxes into a text box. Also, I would like to do something every time the Return / Enter key is pressed in the textbox. The event handler code looks like this:

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

        // do something here
}

      

It looks like if the AcceptsReturn parameter is set to True and the Return key is pressed, this event handler is not called at all. Any other keystroke is recognized properly. If AcceptsReturn is not set to True and the Return key is pressed, the event handler is invoked and pressing the Return key is very easy. The problem is that pressing the return key does not advance the user to a new line in the textbox (as expected). Therefore, I would like the Return key to be pressed to properly advance the user to a new line in the text box, and also I would like to detect that the Return key is pressed. Is my approach wrong? Is there a better way to do this?

+2


source to share


1 answer


KeyDown

is a bubbling event, which means it is hoisted first on the original control ( TextBox

), then on the parent, then on the parent, and so on, until it is processed. When you set the parameter AcceptsReturn

to true, the control handles the Return key, so the event is not bubbled. In this case, you can use a tunnel version of the event: PreviewKeyDown

that is hoisted up on each ancestor of the control from top to bottom before it reaches the source control.



See Routing Strategies on MSDN

+9


source







All Articles