khoa_chung_89
khoa_chung_89

Reputation: 1025

WPF start focusing Editable Combobox

In wpf, I have a combobox which IsEditable=true. In my window, I set focus to that combobox by FocusManager.FocusedElement="{Binding ElementName=myComboBox}" but the combobox is not focusing at all. I can check and see that it's IsFocused property is true but it doesn't turn to editing mode.

With the same code, if I replace the combobox with a textbox, the textbox will get focus and turn to edit mode normally. How can I achieve the same behavior on editable combobox?

Upvotes: 1

Views: 366

Answers (1)

khoa_chung_89
khoa_chung_89

Reputation: 1025

I have found a solution. The combobox got focus but the issue is just it cannot send the focus to the textbox even it's in Editable mode. To do that, I create a custom Combobox control that inherit from Combobox and overriding the OnApplyTemplate method to focus to the textbox inside of combobox. In the example below, I also added IsEditableFocusTextBox property so I can turn this behavior on/off later.

class CustomCombobox : ComboBox
{
    internal bool IsEditableFocusTextBox { get; set; }
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        if (IsFocused && IsEditable && IsEditableFocusTextBox)
        {
            TextBox myControl = (TextBox)GetTemplateChild("PART_EditableTextBox");
            if (myControl != null)
            {
                myControl.Focus();
            }
        }
    }
}

We need to override OnApplyTemplate but not OnGotFocus because at first when focusing, the template is not apply yet so we may not get the textbox.

Upvotes: 2

Related Questions