Give focus to a ComboBox editable in WPF

 
 
  • Gérald Barré

Proper focus management improves the user experience. When a window opens with the first input field already focused, users can start typing immediately without clicking. On a login form, for instance, the username field should be focused right away.

To set focus when opening a window, you can use the FocusManager.FocusedElement property:

XAML
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        FocusManager.FocusedElement="{Binding ElementName=TextBoxUserName}">
    <Grid>
        <TextBox x:Name="TextBoxUserName" />
    </Grid>
</Window>

For an editable ComboBox (IsEditable="True"), this technique does not work as expected. The ComboBox receives focus, but it goes to the dropdown part rather than the internal TextBox. To focus the TextBox directly, retrieve it from the control template and call the Focus method:

C#
var comboBox = MyComboBox;
var textBox = (TextBox) comboBox.Template.FindName("PART_EditableTextBox", comboBox);
if (textBox != null)
{
    textBox.Focus();
}

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?