C# 如何滚动到列表框的底部?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8796747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:29:13  来源:igfitidea点击:

How to scroll to bottom of ListBox?

c#winformslistbox

提问by JYelton

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 SelectionModeis set to none. The user can scroll the list but I would prefer it start out scrolled to the end.

我使用 Winforms ListBox 作为一个小的事件列表,并希望填充它以便最后一个事件(底部)可见。该SelectionMode设置为none。用户可以滚动列表,但我希望它开始滚动到最后。

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.

纵观缺乏对事物的支持喜欢ScrollIntoViewEnsureVisible,我假设我需要创建一个自定义的控件从Control继承; 但是我不确定从那里开始做什么。

Some pointers?

一些指针?

采纳答案by Jon

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

我相信您可以通过TopIndex适当地设置属性来轻松做到这一点。

For example:

例如:

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

回答by user1032613

Scroll to the bottom:

滚动到底部:

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

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

Scroll to the bottom, and select the last item:

滚动到底部,然后选择最后一项:

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

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

回答by Sean Vikoren

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

这就是我对 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(); }
            };
        }
    }
}