WPF: How to programmatically remove focus from a TextBox

前端 未结 9 1765
感动是毒
感动是毒 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-11-30 23:41

    A bit late to the party, but it was helpful to me so here it goes.

    Since .Net 3.0, FrameworkElement has a MoveFocus function which did the trick for me.

    0 讨论(0)
  • 2020-11-30 23:42

    In Windows Phone Development, I just did Focus() or this.Focus() in the PhoneApplicationPage and it worked like a charm.

    0 讨论(0)
  • 2020-11-30 23:45

    Since none of the above answers worked for me and the accepted answer does work only for a keyboard focus, I came to the following approach:

    // Kill logical focus
    FocusManager.SetFocusedElement(FocusManager.GetFocusScope(textBox), null);
    // Kill keyboard focus
    Keyboard.ClearFocus();
    

    Kills both, logical as well as the keyboard focus.

    0 讨论(0)
  • 2020-11-30 23:47

    For me, it's quite tricky, especially when using with LostFocus binding. However, my workaround is to add an empty label and focus on it.

    <Label Name="ResetFocusArea" Focusable="True" FocusVisualStyle="{x:Null}" />
    

    ...

    OnKeyDown(object sender, RoutedEventArgs e)
    {
      //if is Esc
      ResetFocusArea.Focus();
    }
    
    0 讨论(0)
  • 2020-11-30 23:51

    AFAIK, it is not possible to completely remove the focus. Something in your Window will always have the focus.

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
提交回复
热议问题