Search code examples
c#.netwpfxaml

Why doesn't ListView.ScrollIntoView ever work?


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.


Solution

  • 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]);