当我从 ListBox
中删除项目时,它会滚动到所选项目。如果没有选择任何项目,则会滚动到列表顶部。是否可以使其在移除元素时保持静止?
我真的不需要启用选择项目,但即使我将选择模式设置为无,它也会滚动到顶部。
我正在使用 listBox1.Items.Remove(...)
方法来删除项目。
我尝试在删除之前获取 AutoScrollOffset
,然后在删除之后将其设置为与之前相同的 X 和 Y 值,但它不起作用。
我将 Thread.Sleep 和 MessageBox 放在删除项目的方法之后,看起来它在显示我的消息之前滚动,所以它一定是 Items.Remove 导致卷轴。
我的列表框代码如下所示:
private ListBox listBox1 = new ListBox();
this.listBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listBox1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.listBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.listBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
this.listBox1.FormattingEnabled = true;
this.listBox1.IntegralHeight = false;
this.listBox1.ItemHeight = 16;
this.listBox1.Location = new System.Drawing.Point(14, 6);
this.listBox1.Name = "listBox1";
this.listBox1.ScrollAlwaysVisible = true;
this.listBox1.SelectionMode = System.Windows.Forms.SelectionMode.None;
this.listBox1.Size = new System.Drawing.Size(180, 388);
this.listBox1.TabIndex = 0;
this.listBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.listBox1_DrawItem);
在listBox1_DrawItem()
中只是DrawBackground()
、Graphics.DrawString()
、DrawFocusRectangle()
,其他都不重要。
也许有一些我不知道的属性,或者我可能需要安装更新或其他东西......
最佳答案
试试这个:
int tempTopIndex = listBox1.TopIndex;
listBox1.Items.Remove(yourItem);
listBox1.TopIndex = tempTopIndex;
关于c# - 列表框滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6167311/