DrL*_*zer 9 c# wpf user-interface
我一直在寻找类似的问题,找不到任何东西..Caret似乎不可用,我不知道如何深入到文本框或组合框中嵌入的任何控件.
Jef*_*tes 11
您需要PART_EditableTextBox从组合框的控件模板中获取控件.最简单的方法是覆盖OnApplyTemplate派生,ComboBox然后在需要具有此扩展行为的组合框的任何地方使用该派生.
protected void override OnApplyTemplate()
{
var myTextBox = GetTemplateChild("PART_EditableTextBox") as TextBox;
if (myTextBox != null)
{
this.editableTextBox = myTextBox;
}
}
Run Code Online (Sandbox Code Playgroud)
获得文本框后,可以设置插入符号位置,设置SelectionStart为您希望插入符号出现的位置并设置SelectionLength为零.
public void SetCaret(int position)
{
this.editableTextBox.SelectionStart = position;
this.editableTextBox.SelectionLength = 0;
}
Run Code Online (Sandbox Code Playgroud)
如果您不想处理派生类,而只想为任意随机ComboBox设置插入符号,则更简单的方法是在需要时从模板获取文本框(类似于接受的答案),然后直接更新插入符号的位置
var cmbTextBox = (TextBox)myComboBox.Template.FindName("PART_EditableTextBox", myComboBox);
cmbTextBox.CaretIndex = 0;
Run Code Online (Sandbox Code Playgroud)