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
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.
In Windows Phone Development, I just did Focus()
or this.Focus()
in the PhoneApplicationPage and it worked like a charm.
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.
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();
}
AFAIK, it is not possible to completely remove the focus. Something in your Window will always have the focus.
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);
}