How to allow moving focus to and from the WPF WebView control using the Tab key
If you've ever used the WPF Microsoft Edge Legacy based WebView control (not to be confused with the Internet Explorer based WebBrowser control), you may have noticed that you can't use the Tab key to move focus to and from the said control and that only the mouse allows moving focus to and from it. You may also have noticed that using the WebView.Focus() method does not work. Luckily, the WebView contains both a function you can use to move focus to the WebView and an event which fires when the user attempts to move focus away from the WebView using the Tab key.
How to move focus to the WebView using the Tab key
We can moved focus to the WebView using the MoveFocus function of the WebView. In order to detect when the user attempts to focus the WebView, we can use a dummy button to detect the focus and then move it onto the WebView.
Note that the opacity of the button is set to 0 to make it invisible. The height and width of the button is set to 0 to make it take up no space. We can't simply set the button's Visibility to Collapsed as that will prevent the button from receiving Tab focus. From here, we can handle the GotFocus event of the button.
This will give the WebView focus when the button receives focus. To ensure the WebView receives focus in the correct order, put the button just above the WebView, or set its TabIndex to an appropriate value.
How to move focus away from the WebView using the Tab key
To move focus away from the WebView, we can use the MoveFocusRequested event of the WebView. We can check the WebViewControlMoveFocusReason to check if the user Tabbed out of the control (Next) or Shift-Tabbed out of the control (Previous).
And don't forget to add the event handler:
Did this article help you? Do you know of a better way to achieve this? Let us know in the comments!