您可以尝试使用TopIndex
设置顶部可见索引,如下所示:
//Use this ListBox extension for convenience
public static class ListBoxExtension {
public static void SetSelectedWithoutJumping(this ListBox lb, int index, bool selected){
int i = lb.TopIndex;
lb.SetSelected(index, selected);
lb.TopIndex = i;
}
}
//Then just use like this
yourListBox.SetSelectedWithoutJumping(index, true);
您还可以尝试定义一些方法来为索引集合设置 selected 并使用BeginUpdate
andEndUpdate
来避免闪烁:
public static class ListBoxExtension {
public static void SetMultiSelectedWithoutJumping(this ListBox lb, IEnumerable<int> indices, bool selected){
int i = lb.TopIndex;
lb.BeginUpdate();
foreach(var index in indices)
lb.SetSelected(index, selected);
lb.TopIndex = i;
lb.EndUpdate();
}
}
//usage
yourListBox.SetMultiSelectedWithoutJumping(new List<int>{2,3,4}, true);
注意:您也可以在 中使用and BeginUpdate
,但是正如我所说,如果您必须一起选择多个索引,则实现一些扩展方法,例如更好更方便(我们只使用一对and )。EndUpdate
SetSelectedWithoutJumping
SetMultiSelectedWithoutJumping
BeginUpdate
EndUpdate