WPF: How to programmatically remove focus from a TextBox
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 editing to have the text it had when the user started editing, AND I want to remove the focus from the TextBox
.
I don't have any problem setting the text for the value it had in the beginning of the edit.
The problem is to remove the focus of the element. I don't want to move the focus to any other component, I just want the TextBox
to lose focus. Will I have to have an invisible element to set the focus so my TextBox
can lose focus?
in .NET Framework 4 just Keyboard.ClearFocus();
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);
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.
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.