Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

focus

wpf

xbap

I have an app which runs fine as a simple WPF app having an event handler on GotFocus at the main window level like so :

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

However this behaves strangely when set as a XBAP app (almost exactly the same code - the main visual element is Page and not Window but the event is still available and triggered).

In that case (XBAP/wpf browser application) element is always null.

Any ideas? :(

like image 492
Andrei Rînea Avatar asked Jan 20 '23 04:01

Andrei Rînea


2 Answers

Well thanks to a colleague of mine (Bogdan R.) we've discovered that FocusManager.IsFocusScope has different default values for Window (WPF) and Page (XBAP), namely it is false for the latter.

Simply setting FocusManager.IsFocusScope on the Page element fixes the problem.

like image 62
Andrei Rînea Avatar answered Jan 28 '23 04:01

Andrei Rînea


could also try to use Keyboard.FocusedElement instead

like image 27
George Birbilis Avatar answered Jan 28 '23 05:01

George Birbilis