Give focus to a ComboBox editable in WPF

  • .NET
  • .NET

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:

<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:

var comboBox = MyComboBox;
var textBox = (TextBox) comboBox.Template.FindName("PART_EditableTextBox", comboBox);
if (textBox != null)
{
    textBox.Focus();
}
Follow me:
Enjoy this blog?Buy Me A CoffeeDonate with PayPal

Comments

Roman -

Thank you. Your code was helped to me to solve the inverse task.

Leave a reply