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)
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!
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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With