How to set carriage position in WPF text Editable ComboBox

I searched around for a similar question and didn’t find anything .. The carriage doesn’t seem to be available, and I don’t know how to expand it to a text box or any other control built into the combo box.

+8
user-interface c # wpf
source share
2 answers

You need to get to the PART_EditableTextBox control from the list control template. The easiest way to do this is to override OnApplyTemplate when displaying ComboBox , and then use this output wherever you need a combo box with this advanced behavior.

 protected void override OnApplyTemplate() { var myTextBox = GetTemplateChild("PART_EditableTextBox") as TextBox; if (myTextBox != null) { this.editableTextBox = myTextBox; } } 

After you have the text box, you can set the position of the carriage, set the SelectionStart to the location where you want the carriage to be displayed and set SelectionLength to zero.

 public void SetCaret(int position) { this.editableTextBox.SelectionStart = position; this.editableTextBox.SelectionLength = 0; } 
+10
source share

An even simpler way, if you don't want to deal with derived classes and just want to set a caret for any random ComboBox, is to get the text box from the template (similar to the accepted answer) when you need to, and then just update the caret position directly.

 var cmbTextBox = (TextBox)myComboBox.Template.FindName("PART_EditableTextBox", myComboBox); cmbTextBox.CaretIndex = 0; 
+3
source share

All Articles