WinRT KeyDown fired twice when Enter is pressed

Development

9 years ago

I have noticed a very unusual oddity which occurs when handling the KeyDown event. When the user hits the 'Enter' key, the event is actually fired twice (at least this is the case for TextBox and PasswordBox controls on which I have noticed this behavior). Consider the following code snippet:

private void TextBox_KeyDown( object sender, KeyRoutedEventArgs e )
{
    if ( e.Key == VirtualKey.Enter )
    {
        Frame.Navigate( typeof( SomeOtherPage ) );
    }
}

What will actually happen when the user actually presses the 'Enter' key in the TextBox ? As you would expect, the event is fired first time and frame navigates to SomeOtherPage . But right after the execution of the handler finishes, it is called once again with the exact same arguments! The code will get executed again and the frame will once again navigate - which is (probably) not what you actually needed! This behavior is really connected only with the 'Enter' key and it does not seem to be present for other keyboard keys. Luckily the workaround is simple:

private void TextBox_KeyDown( object sender, KeyRoutedEventArgs e )
{
    if ( e.Key == VirtualKey.Enter )
    {
        Frame.Navigate( typeof( SomeOtherPage ) );
        e.Handled = true;
    }
}

By setting KeyRoutedEventArgs ' Handled Property to true we are essentially stopping subsequent bubbling of the event higher up the tree, but this also prevents the event to fire again on the same control. I have reported this issue in the Windows Feedback app for Developer Platform. If you want to support its resolution in future versions of UWP, vote for it by clicking here.