Give focus to a ComboBox editable in WPF

Datetime:2017-04-19 06:29:38         Topic: WPF          Share        Original >>
Here to See The Original Article!!!

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"
        FocusManager.FocusedElement="{Binding ElementName=TextBoxUserName}">
        <TextBox x:Name="TextBoxUserName" />

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)