Why does FocusManager.GetFocusedElement (this) always return null?

I have an application that works fine as a simple WPF application that has an event handler in GotFocus at the main window level, for example:

private void MainWindowGotFocus(object sender, RoutedEventArgs e) { var element = FocusManager.GetFocusedElement(this) as FrameworkElement; if (element != null) { //... 

However, this behaves strangely when installed as an XBAP application (almost exactly the same code), the main visual element is the page, not the window, but the event is still accessible and triggered).

In this case (the XBAP / wpf browser application) is always null.

Any ideas ?: (

+4
source share
2 answers

Well, thanks to my colleague (Bogdan R.), we found that FocusManager.IsFocusScope has different default values โ€‹โ€‹for Window (WPF) and Page (XBAP), namely false.

Just setting FocusManager.IsFocusScope on the page element fixes the problem.

+5
source

may also try using Keyboard.FocusedElement instead

+2
source

Source: https://habr.com/ru/post/1344943/


All Articles