WPF: How to programmatically remove focus from a TextBox

前端 未结 9 1775
感动是毒
感动是毒 2020-11-30 23:04

I want to add a simple (at least I thought it was) behaviour to my WPF TextBox.

When the user presses Escape I want the TextBox he is editi

9条回答
  •  一向
    一向 (楼主)
    2020-12-01 00:02

    The code I have been using :

    // Move to a parent that can take focus
    FrameworkElement parent = (FrameworkElement)textBox.Parent;
    while (parent != null && parent is IInputElement && !((IInputElement)parent).Focusable)
    {
        parent = (FrameworkElement)parent.Parent;
    }
    
    DependencyObject scope = FocusManager.GetFocusScope(textBox);
    FocusManager.SetFocusedElement(scope, parent as IInputElement);
    

提交回复
热议问题