WPF. TextBox focuses after losing focus

39 views Asked by At

Steps

  • Subscribe TextBox focus events
_associatedObject.GotKeyboardFocus += OnAssociatedObjectGotKeyboardFocus;
_associatedObject.LostKeyboardFocus += OnAssociatedObjectLostKeyboardFocus;

_associatedObject.GotFocus += (s,e) =>
{
    System.Diagnostics.Debug.WriteLine("GotFocus");
};

_associatedObject.LostFocus += (s, e) =>
{
    System.Diagnostics.Debug.WriteLine("LostFocus");
};

_associatedObject.IsKeyboardFocusedChanged += (s, e) =>
{
    System.Diagnostics.Debug.WriteLine("IsKeyboardFocusedChanged");
};

_associatedObject.IsKeyboardFocusWithinChanged += (s, e) =>
{
    System.Diagnostics.Debug.WriteLine("IsKeyboardFocusWithinChanged");
};
  • Raise LostFocusEvent after LostKeyboardFocus
private void OnAssociatedObjectLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    _associatedObject.RaiseEvent(new RoutedEventArgs(UIElement.LostFocusEvent));
    Keyboard.ClearFocus();
    System.Diagnostics.Debug.WriteLine("LostKeyboardFocus");
}
  • Open the program and click on the TextBox;
  • After the element has focus, click on the desktop, or in any other application, to remove focus from the TextBox element;
  • Return focus to your application again.

Expectations

After focusing the window, nothing should be added to the debug window because the element has been LostFocus.

Result

IsKeyboardFocusWithinChanged
IsKeyboardFocusedChanged
GotKeyboardFocus
IsKeyboardFocusWithinChanged
IsKeyboardFocusedChanged
LostFocus
LostKeyboardFocus
LostFocus

enter image description here

0

There are 0 answers