How to scroll to bottom of ListBox?

前端 未结 3 2034
眼角桃花
眼角桃花 2020-12-10 00:27

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. T

3条回答
  •  情书的邮戳
    2020-12-10 01:02

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

提交回复
热议问题