Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyDown Event not fired for TextBox in UWP

When I press the Enter key, the KeyDown event for the TextBox is not fired if its AcceptsReturn property is set to true. How can I identify when the Enter key is pressed for a TextBox with AcceptsReturn set to true?

like image 566
venkatesan r Avatar asked Dec 15 '22 06:12

venkatesan r


2 Answers

If you are looking to completely disable the new line (like @ruffin wants to), subscribe to the PreviewKeyDown event via code behind and set e.Handled to true.

    public MyControl()
    {
        InitializeComponent();

        var keyeventHandler = new KeyEventHandler(TextBox_KeyDown);
        uiText.AddHandler(PreviewKeyDownEvent, keyeventHandler, handledEventsToo: true);
    }

    private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        if (e.Key == Windows.System.VirtualKey.Enter)
            e.Handled = true;
    }
like image 59
Alisa Esh Avatar answered Dec 28 '22 09:12

Alisa Esh


I tried the below code, and its works for me,

var textBox = new TextBox();
KeyEventHandler keyeventHandler = new KeyEventHandler(textBox_KeyDown);

textBox.AddHandler(TextBox.KeyDownEvent, keyeventHandler, true);

private void textBox_KeyDown(object sender, KeyEventArgs e)
{
*** now Enter Key gets fired eventhough when i set AcceptsReturn as True ***
}
like image 28
venkatesan r Avatar answered Dec 28 '22 09:12

venkatesan r