I am trying to scroll into view so that the very last item in a vertical listivew is always showing, but ListView.ScrollIntoView() never works.
I have tried:
button1_Click(object sender, EventArgs e)
{
activities.Add(new Activities()
{
Time = DateTime.Now,
Message = message
});
ActivityList.ItemsSource = activities;
// Go to bottom of ListView.
ActivityList.SelectedIndex = ActivityList.Items.Count;
ActivityList.ScrollIntoView(ActivityList.SelectedIndex);
}
I have also tried:
ActivityList.ScrollIntoView(ActivityList.Items.Count)
, and ActivityList.ScrollIntoView(ActivityList.Items.Count + 1);
but nothing is working.
Please help. This is really annoying. And the documentation isn't very helpful in this case.
You're passing in the index when the method expects the item object. Try this to scroll to the selected item.
ActivityList.ScrollIntoView(ActivityList.SelectedItem);
If you want to scroll to the last item, you can use this
ActivityList.ScrollIntoView(ActivityList.Items[ActivityList.Items.Count - 1]);
It's got something to do with the internal list representation, namely, the items are not yet in place when you call the ScrollIntoView().
After many attempts, this is what I finally came up with and this seems to work: attach two handlers to every ListBox/ListView:
<ListBox x:Name="YourList" ... Loaded="YourList_Loaded" SelectionChanged="YourList_SelectionChanged">
and
void YourList_Loaded(object sender, RoutedEventArgs e) {
if (YourList.SelectedItem != null)
YourList.ScrollIntoView(YourList.SelectedItem);
}
void YourList_SelectionChanged(object sender, SelectionChangedEventArgs e) {
if (YourList.SelectedItem != null)
YourList.ScrollIntoView(YourList.SelectedItem);
}
The second handler you can't do without. You can't call ScrollIntoView()
immediately after you set the selected item, it's not yet ready. You have to allow the list to inform you when it has actually changed the item. The first handler depends on the circumstances, if you have problems with the selection showing up after the initial loading of the list contents, you might need it, too.
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