WPF: How to programmatically remove focus from a TextBox

前端 未结 9 1767
感动是毒
感动是毒 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:01

    You can set the focus to a focusable ancestor. This code will work even if the textbox is inside a template with no focusable ancestors inside that same template:

    DependencyObject ancestor = textbox.Parent;
    while (ancestor != null)
    {
        var element = ancestor as UIElement;
        if (element != null && element.Focusable)
        {
            element.Focus();
            break;
        }
    
        ancestor = VisualTreeHelper.GetParent(ancestor);
    }
    

提交回复
热议问题