Search code examples
c#uwpkeydownonkeydown

KeyDown event doesn't trigger from selected grid in UWP


I'm working on custom control like calendar, where I have a panel as month view in which Grid cells are arranged as Date cells. The grid has a content presenter with TextBlock as a content template. Everything working fine. Pointerpressed, pointerReleased and OnTapped override methods are working fine for Grid but OnKeyDown override method or KeyDown event doesn't trigger from it. I also tried with PreviewKeyDown. Please help me to overcome this issue.


Solution

  • The key down event only trigger from keyboard focused control. And the Grid is not a control and the Grid is Panel. In UWP, only the control can set focus.

    You can write a empty control and add it to Grid to set the control focus.

    class Foo : Control
    {
        protected override void OnKeyDown(KeyRoutedEventArgs e)
        {
            Debug.WriteLine("Foo key down");
        }
    }
    
        <Grid x:Name="Grid2" Margin="10,10,10,10" Width="100" Background="#565656" HorizontalAlignment="Right" 
              KeyDown="Grid2_OnKeyDown">
            <local:Foo x:Name="Foo"></local:Foo>
        </Grid>
    

    You can write any code to help debug when the Grid2 key down.

        private void Grid2_OnKeyDown(object sender, KeyRoutedEventArgs e)
        {
            Debug.WriteLine("Grid2 key down");
        }
    

    And then you can set the Foo property focus when the Grid2 clicked.

        private async void Grid2_OnPointerReleased(object sender, PointerRoutedEventArgs e)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Foo.Focus(FocusState.Keyboard); });
        }
    

    Try to run the code and you can see the output windows show the message when you click the Grid2 and press key.

    But why I write the code in dispatcher, because I should make the Foo control get focus. And if I do not use dispatcher and the pointer focus will in Grid and not any UIElement focus keyboard.