How to scroll to bottom of ListBox?

2019-01-18 08:30发布

问题:

I am using a Winforms ListBox as a small list of events, and want to populate it so that the last event (bottom) is visible. The SelectionMode is set to none. The user can scroll the list but I would prefer it start out scrolled to the end.

Looking at the lack of support for things like ScrollIntoView, EnsureVisible, I am assuming I will need to create a custom control that inherits from ListBox; however I'm not sure what to do from there.

Some pointers?

回答1:

I believe you can do that easily by setting the TopIndex property appropriately.

For example:

int visibleItems = listBox.ClientSize.Height / listBox.ItemHeight;
listBox.TopIndex = Math.Max(listBox.Items.Count - visibleItems + 1, 0);


回答2:

Scroll to the bottom:

listbox.TopIndex = listbox.Items.Count - 1;

Scroll to the bottom, and select the last item:

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



回答3:

This is what I ended up with for WPF (.Net Framework 4.6.1):

Scroll.ToBottom(listBox);

Using the following utility class:

public partial class Scroll
{
    private static ScrollViewer FindViewer(DependencyObject root)
    {
        var queue = new Queue<DependencyObject>(new[] { root });

        do
        {
            var item = queue.Dequeue();
            if (item is ScrollViewer) { return (ScrollViewer)item; }
            var count = VisualTreeHelper.GetChildrenCount(item);
            for (var i = 0; i < count; i++) { queue.Enqueue(VisualTreeHelper.GetChild(item, i)); }
        } while (queue.Count > 0);

        return null;
    }

    public static void ToBottom(ListBox listBox)
    {
        var scrollViewer = FindViewer(listBox);

        if (scrollViewer != null)
        {
            scrollViewer.ScrollChanged += (o, args) =>
            {
                if (args.ExtentHeightChange > 0) { scrollViewer.ScrollToBottom(); }
            };
        }
    }
}