Keyboard.Focus does not work on text box in WPF
As a workaround, you could try using the Dispatcher
to set the focus at a later DispatcherPriority, such as Input
Dispatcher.BeginInvoke(DispatcherPriority.Input,
new Action(delegate() {
SearchCriteriaTextBox.Focus(); // Set Logical Focus
Keyboard.Focus(SearchCriteriaTextBox); // Set Keyboard Focus
}));
From the description of your problem, it sounds like you don't have Keyboard focus set. WPF can have multiple Focus Scopes, so multiple elements can have Logical Focus (IsFocused = true
), however only one element can have Keyboard Focus and will receive keyboard input.
The code you posted should set the focus correctly, so something must be occurring afterwards to move Keyboard Focus out of your TextBox
. By setting focus at a later dispatcher priority, you'll be ensuring that setting keyboard focus to your SearchCriteriaTextBox
gets done last.
Building on Rachel's solution there is a simpler way.
in XAML add to the TextBox Loaded="Got_Loaded"
and in code behind
private void Got_Loaded(object sender, RoutedEventArgs e)
{
Keyboard.Focus(((TextBox)sender));
}