Set focus on textbox in WPF Set focus on textbox in WPF wpf wpf

Set focus on textbox in WPF


In XAML:

<StackPanel FocusManager.FocusedElement="{Binding ElementName=Box}">   <TextBox Name="Box" /></StackPanel>


Nobody explained so far why the code in the question doesn't work. My guess is that the code was placed in the constructor of the Window. But at this time it's too early to set the focus. It has to be done once the Window is ready for interaction. The best place for the code is the Loaded event:

public KonsoleWindow() {  public TestWindow() {    InitializeComponent();    Loaded += TestWindow_Loaded;  }  private void TestWindow_Loaded(object sender, RoutedEventArgs e) {    txtCompanyID.Focus();  }}


try FocusManager.SetFocusedElement

FocusManager.SetFocusedElement(parentElement, txtCompanyID)