我一直在寻找类似的问题但找不到任何东西。 .Caret似乎不可用,我不知道如何深入到文本框或组合框中嵌入的任何控件。
答案 0 :(得分:10)
您需要从组合框的控件模板中获取PART_EditableTextBox
控件。最简单的方法是在OnApplyTemplate
的派生中覆盖ComboBox
,然后在需要具有此扩展行为的组合框的任何地方使用该派生。
protected void override OnApplyTemplate()
{
var myTextBox = GetTemplateChild("PART_EditableTextBox") as TextBox;
if (myTextBox != null)
{
this.editableTextBox = myTextBox;
}
}
获得文本框后,您可以设置插入符号位置,将SelectionStart
设置为您希望显示插入符号的位置,并将SelectionLength
设置为零。
public void SetCaret(int position)
{
this.editableTextBox.SelectionStart = position;
this.editableTextBox.SelectionLength = 0;
}
答案 1 :(得分:4)
更简单的方法是,如果你不想处理派生类,只想为任何随机的ComboBox设置插入符号,就是从模板中获取文本框(类似于接受的答案)当你需要它,然后直接更新插入位置。
var cmbTextBox = (TextBox)myComboBox.Template.FindName("PART_EditableTextBox", myComboBox);
cmbTextBox.CaretIndex = 0;