Setting Initial Focus in XAML

Last time we looked at a tricky problem of setting the initial focus to a specific item in a populated WPF ListView. Most of the time, however, we just want to set the initial focus to a control (like a TextBox or a Button) in our UI. There are a couple of ways to accomplish this.

  1. Hook the Window’s Loaded event and set the focus to the desired control in the code-behind handler
  2. Use FocusManager.FocusedElement

The second solution is easier and can all be done in XAML. For example:

<Window …

    FocusManager.FocusedElement="{Binding ElementName=myTextBox}">

    …

    <TextBox x:Name=”myTextBox”/>

</Window>

Hope this helps. -Tan