如何防止Listbox跳至tem? [英] How to prevent Listbox jumps to ítem?

查看:95
本文介绍了如何防止Listbox跳至tem?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设在WinForms中,我有一个启用了multiselect的列表框,该列表框包含50个项目,并且仅选择了列表框的第一项...

Suppose that in a WinForms I have a Listbox with multiselect enabled, listbox contains 50 items and only the first item of the listbox is selected...

...然后如果我选择(使用SetSelected方法)最后一个项目,则列表框将跳到底部(连同垂直滚动条一起显示).

...Then if I select (using SetSelected method) the last item then the listbox will jump to bottom (together with the vertical scroll) to show me that item.

我只希望列表框保持在原来的位置,尽管我使用SetSelected选择其他项目,但我不希望列表框每次都上下移动.

I just want that the listbox stays in the position that it was, while I use SetSelected to select other items, I don't want the listbox moving up and down everytime.

那么,当我使用SetSelected方法时,如何防止列表框和列表框v.滚动条跳至ítem? (上下两个方向)

So how I can prevent the Listbox and the listbox v. scrollbar to jump to ítem when I use SetSelected method? (in both directions up or down)

我希望也许我可以使用 WinAPI 的功能来做到这一点.

I hope that maybe I could use a function of WinAPI to do this.

推荐答案

您可以尝试使用TopIndex设置顶部可见索引,如下所示:

You can try using the TopIndex to set the top visible index like this:

//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);

您还可以尝试定义一些方法来设置为索引集合选择的方法,并使用BeginUpdateEndUpdate避免闪烁:

You can also try defining some method to set selected for a collection of indices and use the BeginUpdate and EndUpdate to avoid flickering:

 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);

注意:您也可以在SetSelectedWithoutJumping中使用BeginUpdateEndUpdate,但是正如我所说,如果必须同时选择多个索引,则可以实现一些扩展方法,例如SetMultiSelectedWithoutJumping更好,更方便(我们只使用一对BeginUpdateEndUpdate).

NOTE: You can also use the BeginUpdate and EndUpdate in the SetSelectedWithoutJumping, however as I said, if you have to select multi-indices together, implementing some extension method like SetMultiSelectedWithoutJumping is better and more convenient (we just use 1 pair of BeginUpdate and EndUpdate).

这篇关于如何防止Listbox跳至tem?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆