I am banging my head on what looks like such a simple problem to fix in wpf but i have yet to discover why i can\'t get my app to behave according to my plan.
I have a
If it helps anyone I had this problem and my application had a main window with multiple user controls placed in separate grids with a visibility data binding. Because the grids were there when the application was built the .Focus() called on Loaded or Constructor would be called at the build time, not at visibility time.
Anyhow I fixed it by calling .Focus() on MouseEnter event of the grid. Works fine for me.
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));
}