Is there a way to bind to Keyboard.FocusedElement?

I would like to have a property that is always bound to the current lumped control.

I saw two ways to get the current focused control.

One uses Keyboard.FocusedElement. The second is a visual tree.

Since I want to know every time a focused element changes, a visual tree walk seems to work a lot of code all the time.

But Keyboard.FocusedElement does not implement INotifyPropertyChanged. Therefore, I can’t just get attached to it normally.

Is there a way to get him to tell me when he will change?

(Or is there any other way to have a property that is always set for the current focused control?)

NOTE. . I can add an event to each control and update it. But I have a lot of control. I want not to apply an event to each of them.

+5
source share
1 answer

You can try to subscribe to the Attached Keyboard.GotKeyboardFocus event

Occurs when an item receives keyboard focus.

Here is an example that subscribes to this OnStartup event. You can use the attached behavior that does this, and updates the attached property to which you can bind, for example.

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        EventManager.RegisterClassHandler(typeof(UIElement),
            Keyboard.GotKeyboardFocusEvent,
            new RoutedEventHandler(Keyboard_GotKeyboardFocus), true);

        base.OnStartup(e);
    }

    private void Keyboard_GotKeyboardFocus(object sender, RoutedEventArgs e)
    {
        Debug.WriteLine(e.OriginalSource);
    }
}
+6
source

All Articles