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
A slightly different approach to those presented so far.
You could use the ScrollViewer
ScrollChanged
event and watch for the content of the ScrollViewer
getting larger.
private void ListBox_OnLoaded(object sender, RoutedEventArgs e)
{
var listBox = (ListBox) sender;
var scrollViewer = FindScrollViewer(listBox);
if (scrollViewer != null)
{
scrollViewer.ScrollChanged += (o, args) =>
{
if (args.ExtentHeightChange > 0)
scrollViewer.ScrollToBottom();
};
}
}
This avoids some issues with the binding to the ListBox
ItemsSource
changing.
The ScrollViewer
can also be found without making the assumption that the ListBox
is using the default control template.
// Search for ScrollViewer, breadth-first
private static ScrollViewer FindScrollViewer(DependencyObject root)
{
var queue = new Queue(new[] {root});
do
{
var item = queue.Dequeue();
if (item is ScrollViewer)
return (ScrollViewer) item;
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(item); i++)
queue.Enqueue(VisualTreeHelper.GetChild(item, i));
} while (queue.Count > 0);
return null;
}
Then attach this to the ListBox
Loaded
event:
This could be easily modified to be an attached property, to make it more general purpose.