3

我正在将项目添加到 ac# 列表框中,并希望始终将其滚动到添加到列表中的最后一个项目,以便它可见。该列表通常会超出可用空间,因此将显示垂直滚动条,并且当​​用户可以移动它时,我需要使用新项目再次强制它跳转到末尾。我发现的唯一有用的方法是将 TopIndex 属性与框中的行一起使用 - 可以显示的行数。我使用下面的代码可以正常工作,除非其中一行太长,在这种情况下,水平滚动条会占用大约最后 2 个项目的空间。如果我能弄清楚是否显示了水平条,我可以改变计算中的行数来解释它。

        LB1.Items.Add(strText);
        LB1.TopIndex = Math.Max(0,lbXmlMsg.Items.Count - 10); // 10 rows visible

要确保新项目可见,这似乎需要做很多工作。我在这里错过了什么吗?

4

3 回答 3

1

I'm not sure how to easily detect whether the horizontal scrollbar is showing but here's an extension method which will let you scroll to the last item and not raise the SelectedIndexChanged event.

public static void ScrollToLastItem(this ListBox lb, EventHandler eventHandler)
{
    lb.SelectedIndexChanged -= eventHandler;
    lb.SelectedIndex = lb.Items.Count - 1;
    lb.SelectedIndex = -1;
    lb.SelectedIndexChanged += eventHandler;
}

You can use it like this (passing in your SelectedIndexChanged event handler).

myListBox.ScrollToLastItem(myListBox_SelectedIndexChanged);

It can be easily modified to scroll to any item index if you don't want it to go just to the final item.

于 2013-07-28T23:15:02.330 回答
1

您可以通过调用检查水平滚动条是否可见

LB1.HorizontalScrollbar

根据 OP 的评论,上述方法不起作用。

我还要说硬编码数字是不好的做法,你可以这样做: 如何滚动到 ListBox 的底部?

然后这是一种自动滚动http://www.csharp-examples.net/autoscroll/

我没有尝试过任何这些,但它们应该可以工作。

如果您切换到 ListView,则它的EnsureVisible功能可以完全满足您的要求。

于 2013-07-28T21:40:21.053 回答
0

添加项目后如何,您执行以下操作

listBox1.SelectedIndex = listBox1.Items.Count - 1;

它将确保最后一个项目是可见的。

于 2013-07-28T21:58:48.313 回答