Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't ListView.ScrollIntoView ever work?

Tags:

c#

.net

wpf

xaml

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.

like image 564
jay_t55 Avatar asked Jun 05 '13 14:06

jay_t55


2 Answers

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]);
like image 110
keyboardP Avatar answered Oct 04 '22 04:10

keyboardP


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.

like image 34
Gábor Avatar answered Oct 04 '22 05:10

Gábor