Give focus to a ComboBox editable in WPF

 
 
  • Gérald Barré

Good control focus management improves the user experience. Indeed, if at the opening of a window the first TextBox is selected, the user can directly enter text without having to click in the field. For example, when I click on the login button, I expect to enter my login directly.

To set the 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>

In the case of an editable ComboBox (IsEditable="True"), this technique does not work as desired. The ComboBox has the focus, but it's the dropdown part that has the focus and not the TextBox. To give focus to the TextBox, you must retrieve it in the control template and then use 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?Buy Me A Coffee💖 Sponsor on GitHub