KeyDown event not raising from a grid

孤人 提交于 2019-11-30 20:25:52

Right this is weird. This is clearly a focus problem, still I can not understand why the grid do not take Focus, even when we click on it.

Though there is a workaround: create an handler for the loaded event of the grid:

<Grid x:Name="theGrid" KeyDown="Grid_KeyDown_1" Focusable="True" Loaded="TheGrid_OnLoaded">

And then force focus in your code behind:

    private void TheGrid_OnLoaded(object sender, RoutedEventArgs e)
    {
        theGrid.Focus();
    }

Your keydown event will work after that. Hope it helps.

Nagev

I had the same issue with a Universal Windows Platform (UWP) app. I attached the event to a grid in XAML but it would only work when the focus was on the TextBox. I found the answer (not just a workaround) on MSDN: https://social.msdn.microsoft.com/Forums/en-US/56272bc6-6085-426a-8939-f48d71ab12ca/page-keydown-event-not-firing?forum=winappswithcsharp

In summary, according to that post, the event won't fire because when focus to the TextBox is lost, it's passed higher up so the Grid won't get it. Window.Current.CoreWindow.KeyDown should be used instead. I've added my event handlers to the page loaded event like this:

private void Page_Loaded(object sender, RoutedEventArgs e)
{
    Window.Current.CoreWindow.KeyDown += coreWindow_KeyDown;
    Window.Current.CoreWindow.KeyUp += CoreWindow_KeyUp;
}

This works as expected for me.

I tried using the Focus Method too, to no avail, until I set the Focusable property to true ( It was default to False. )

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!