UWP: How to fix losing focus when a grid or other non-focusable control is clicked

Ever noticed a situation where, in your UWP app, the user clicks an empty area in a page or other non-focusable control, and then all of a sudden the whole page loses focus, completely breaking any KeyDown or PreviewKeyDown events you've set up? Never remember this happening with WPF and Windows Forms? 

That's because this is new behaviour with UWP - where, if you click on an empty space, focus will go all the way back to the root ScrollViewer which houses all your content - this ScrollViewer is provided by the platform and not something you can control. Luckily, this issue can be easily fixed by overriding the page's pointer event handling. This was reported here and fixed in WinUI 3, but not UWP.

The fix

To fix this, we can override the page's handling of pointer events, to stop the default behaviour where it passes focus on to the root ScrollViewer. Let's first add the event handler for the PointerPressed event and set a background (note that you can set the background to whatever you want; it is just there to stop clicks from going through to the root ScrollViewer so that we can catch them and handle them):

XAML:

PointerPressed="Page_PointerPressed" Background="Transparent"

VB:

AddHandler myPage.PointerPressed, AddressOf Page_PointerPressed

myPage.Background = New SolidColorBrush(Windows.UI.Colors.Transparent)

C#:

myPage.PointerPressed += Page_PointerPressed;

myPage.Background = new SolidColorBrush(Windows.UI.Colors.Transparent);


Then, in the event handler, simply mark the event as handled:

VB:

Private Sub Page_PointerPressed(sender As Object, e As PointerRoutedEventArgs)

e.Handled = True

End Sub

C#:

private void Page_PointerPressed(object sender, PointerRoutedEventArgs e)

{

e.Handled = true;

}


And that should do it - you should now notice that, if you click or tap an empty spot on your page, the currently focused element should not lose focus and all your key events should continue to work!

Comments

Popular posts from this blog

How to show placeholder text in a WPF TextBox in C# and VB

How to use modern icons in XAML in WPF on Windows 10 and 11

How to enable dark title bar in WPF and Windows Forms/WinForms apps in C# and VB

Microsoft WebView2: How to check if the WebView2 runtime is installed in C# and VB

How to change the colour of a WPF or Windows Forms/WinForms title bar in Windows 11 in C# and VB