KeyDown event does not rise from the grid

Here I have an approximate window with a grid. I need to capture an event when a key is pressed. But it does not rise when I press the grid area and then press the key. It will only work if the Textbox is concentrated. I know this will work if I take it from the window. But I have another application with a small number of user controllers, and I need to capture it from different ones. I tried setting Focusable.false for Window and true for Grid, but that doesn't help. Any solutions?

<Window x:Class="Beta.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" Closed="Window_Closed_1" Focusable="False"> <Grid KeyDown="Grid_KeyDown_1" Focusable="True"> <TextBox x:Name="tbCount" HorizontalAlignment="Left" Height="35" Margin="310,49,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="83"/> </Grid> 

+6
source share
3 answers

True, this is strange. This is clearly a focus problem, but I cannot understand why the grid does not accept focus, even when we click on it.

Although there is a workaround: create a handler for the loaded grid event:

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

And then fix the focus in the code:

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

After that, your key event will work. Hope this helps.

+3
source

I had the same issue with Universal Windows Platform (UWP) application. I bound the event to a grid in XAML, but it will only work if the focus is 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

Thus, according to this message, the event will not fire, because when the focus on the TextBox is lost, it will go higher, so the Grid will not receive it. Window.Current.CoreWindow.KeyDown should be used instead. I added event handlers to the page loading event as follows:

 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.

+6
source

I also tried using the Focus method until I set the Focusable property to true (the default is False.)

+2
source

All Articles