Scroll WPF Listview to specific line Scroll WPF Listview to specific line wpf wpf

Scroll WPF Listview to specific line


Someone told me an even better way to scroll to a specific line, which is easy and works like charm.
In short:

public void ScrollToLastItem(){  lv.SelectedItem = lv.Items.GetItemAt(rows.Count - 1);  lv.ScrollIntoView(lv.SelectedItem);  ListViewItem item = lv.ItemContainerGenerator.ContainerFromItem(lv.SelectedItem) as ListViewItem;  item.Focus();}

The longer version in MSDN forums:


I think the problem here is that the ListViewItem is not created yet if the line is not visible. WPF creates the Visible on demand.

So in this case you probably get null for the item, do you?(According to your comment, you do)

I have found a link on MSDN forums that suggest accessing the Scrollviewer directly in order to scroll. To me the solution presented there looks very much like a hack, but you can decide for yourself.

Here is the code snippet from the link above:

VirtualizingStackPanel vsp =    (VirtualizingStackPanel)typeof(ItemsControl).InvokeMember("_itemsHost",   BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic, null,    _listView, null);double scrollHeight = vsp.ScrollOwner.ScrollableHeight;// itemIndex_ is index of the item which we want to show in the middle of the viewdouble offset = scrollHeight * itemIndex_ / _listView.Items.Count;vsp.SetVerticalOffset(offset);


I made some changes to Sam's answer. Note that I wanted to scroll to the last line. Unfortunately the ListView sometiems just displayed the last line (even when there were e.g. 100 lines above it), so this is how I fixed that:

    public void ScrollToLastItem()    {        if (_mainViewModel.DisplayedList.Count > 0)        {            var listView = myListView;            listView.SelectedItem = listView.Items.GetItemAt(_mainViewModel.DisplayedList.Count - 1);            listView.ScrollIntoView(listView.Items[0]);            listView.ScrollIntoView(listView.SelectedItem);            //item.Focus();        }    }

Cheers