How to set caret position on a WPF text Editable ComboBox
I have searched around for a similar question and couldn't find anything. .Caret doesn't appear to be available and开发者_开发问答 I don't know how to drill down to the textbox or whatever control is embedded within the combobox.
You need to get at the PART_EditableTextBox
control from the combo box's control template. The easiest way to do this would be to override OnApplyTemplate
in a derivation of ComboBox
and then use that derivation wherever you need a combo box with this extended behaviour.
protected void override OnApplyTemplate()
{
var myTextBox = GetTemplateChild("PART_EditableTextBox") as TextBox;
if (myTextBox != null)
{
this.editableTextBox = myTextBox;
}
}
Once you have the text box, you can set the caret position, set SelectionStart
to the location where you'd like the caret to appear and set SelectionLength
to zero.
public void SetCaret(int position)
{
this.editableTextBox.SelectionStart = position;
this.editableTextBox.SelectionLength = 0;
}
An even easier way, if you don't want to deal with derived classes, and just want to set the caret for any random ComboBox, is to get the text box from the template (similar to the accepted answer) when you need it, and then just update the caret position directly.
var cmbTextBox = (TextBox)myComboBox.Template.FindName("PART_EditableTextBox", myComboBox);
cmbTextBox.CaretIndex = 0;
精彩评论