How to scroll a list in a ListBox?

I use Winforms ListBox as a small list of events and I want to populate it so that the last event is visible (below). SelectionMode set to none. The user can scroll through the list, but I would prefer it to start from scrolling to the end.

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

Some pointers?

+57
c # winforms listbox
Jan 09 '12 at 23:40
source share
3 answers

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

For example:

 int visibleItems = listBox.ClientSize.Height / listBox.ItemHeight; listBox.TopIndex = Math.Max(listBox.Items.Count - visibleItems + 1, 0); 
+85
Jan 09 2018-12-12T00:
source share

Scroll down:

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

Scroll down and select the last item:

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

+51
Oct 29 '15 at 16:04
source share

Here's 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(); } }; } } } 
+1
Oct 31 '18 at 22:43
source share



All Articles