Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF ListBox Scroll to end automatically

In my application, I have a ListBox with items. The application is written in WPF.

How can I scroll automatically to the last added item? I want the ScrollViewer to be moved to the end of the list when new item has been added.

Is there any event like ItemsChanged? (I don't want to use the SelectionChanged event)

like image 267
niao Avatar asked Feb 25 '10 21:02

niao


4 Answers

Try this:

lstBox.SelectedIndex = lstBox.Items.Count -1;
lstBox.ScrollIntoView(lstBox.SelectedItem) ;

In your MainWindow, this will select and focus on last item on the list!

like image 100
Oz Mayt Avatar answered Oct 23 '22 04:10

Oz Mayt


The easiest way to do this:

if (VisualTreeHelper.GetChildrenCount(listView) > 0)
{
    Border border = (Border)VisualTreeHelper.GetChild(listView, 0);
    ScrollViewer scrollViewer = (ScrollViewer)VisualTreeHelper.GetChild(border, 0);
    scrollViewer.ScrollToBottom();
}

It is always working for ListView and ListBox controls. Attach this code to the listView.Items.SourceCollection.CollectionChanged event and you have fully automatic auto-scrolling behaviour.

like image 31
Mateusz Myślak Avatar answered Oct 23 '22 03:10

Mateusz Myślak


Keep in mind that listBox.ScrollIntoView(listBox.Items[listBox.Items.Count - 1]); works only if you have no duplicate items. If you have items with the same contents it scrolls down to the first find.

Here is the solution I found:

ListBoxAutomationPeer svAutomation = 
    ListBoxAutomationPeer)ScrollViewerAutomationPeer.
        CreatePeerForElement(myListBox);

IScrollProvider scrollInterface =
    (IScrollProvider)svAutomation.GetPattern(PatternInterface.Scroll);

System.Windows.Automation.ScrollAmount scrollVertical = 
    System.Windows.Automation.ScrollAmount.LargeIncrement;

System.Windows.Automation.ScrollAmount scrollHorizontal = 
    System.Windows.Automation.ScrollAmount.NoAmount;

// If the vertical scroller is not available, 
// the operation cannot be performed, which will raise an exception. 
if (scrollInterface.VerticallyScrollable)
    scrollInterface.Scroll(scrollHorizontal, scrollVertical);
like image 44
NovaLogic Avatar answered Oct 23 '22 05:10

NovaLogic


The best solution is to use the ItemCollection object inside the ListBox control this collection was specially designed to content viewers. It has a predefined method to select the last item and keep a cursor position reference....

myListBox.Items.MoveCurrentToLast();
myListBox.ScrollIntoView(myListBox.Items.CurrentItem);
like image 29
Givanio Avatar answered Oct 23 '22 03:10

Givanio