2013-07-18 28 views
0

我有一个组合框的Winforms应用程序,它的DropDownStyle设置为Simple我想停止Combobox.Items.Clear()移动我的文本光标

当我呼叫this.InputComboBox.Items.Clear()时,它会将文本插入光标从任何地方移动到输入框的开头,尽管文本内容不变。为什么会发生这种情况,我可以预防它吗?

回答

0

您可以通过使用SelectionStartSelectionLength(例如,)来为您的组合框实施一点状态管理来实现此目的。

int _selectionStart = 0; 
private void Clear_Click(object sender, EventArgs e) 
{ 
    ... 
    this.comboBox1.Items.Clear(); 
    this.comboBox1.Focus(); 
    this.comboBox1.SelectionStart = _selectionStart; 
    this.comboBox1.SelectionLength = 0; 
} 

private void InputComboBox_KeyDown(object sender, KeyEventArgs e) 
{ 
    _selectionStart = this.InputComboBox.SelectionStart; 
} 

...这不处理的鼠标,所以你需要连接额外的事件,并捕获_selectionStart那里。

+0

我目前的解决方法与此类似,但我想知道为什么会发生这种情况。我希望完全避免这种行为,但如果必须的话,我可以忍受。 – recursive

1

看起来像这是默认行为ClearInternal在ObjectCollection类中调用的方法。

如果你没有大量的项目,你可以轻松地创建一个可以使用的扩展,而不是Clear方法。喜欢的东西:

public static void SafeClearItems(this ComboBox comboBox) 
    { 
     foreach (var item in new ArrayList(comboBox.Items)) 
     { 
      comboBox.Items.Remove(item); 
     } 
    } 

默认清除方法是比这更好的,它的内部使用Array.Clear,但你不能使用,因为你没有访问ObjectCollection的InnerList其中的项目实际上是存储。否则,我认为你被困在当前的解决方法。

相关问题