How to add a focus to an editable ComboBox in WPF

后端 未结 4 2019
离开以前
离开以前 2021-01-12 08:17

I am using an editable ComboBox in wpf but when i try to set focus from C# code, it is only shows selection. but i want to go for edit option (cursor should display for user

4条回答
  •  清酒与你
    2021-01-12 08:41

    Based on the answer of user128300 above I came up with a slightly simpler solution. In the constructor or ContextChangedHandler the code is waiting for the control to be loaded before putting the focus on the UI element

    myComboBox.GotFocus += MyComboBoxGotFocus;
    myComboBox.Loaded += (o, args) => { myComboBox.Focus(); };
    

    Then in the focus even handler I select all the text from the start to the end

    private void MyComboBoxGotFocus(object sender, RoutedEventArgs e)
    {
        var textBox = myComboBox.Template.FindName("PART_EditableTextBox", myComboBox) as TextBox;
        if (textBox != null)
            textBox.Select(0, textBox.Text.Length);
    }
    

    In xaml the combobox is editable. By selecting all the text when user type a key it is resetting the previous value

    
    

提交回复
热议问题