Windows 10 ScrollIntoView() is not scrolling to the items in the middle of a listview

后端 未结 3 973
渐次进展
渐次进展 2020-11-28 10:04

I have a Listview with 20 items in it. I want to scroll the Listview programmatically.

ListView?.ScrollIntoView(ListView.Items[0])

will scr

3条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 10:44

    I solve this like:

     var sv = new ScrollViewerHelper().GetScrollViewer(listView);
            sv.UpdateLayout();
            sv.ChangeView(0, sv.ExtentHeight, null);
    

    And the GetScrollViewer method:

    public ScrollViewer GetScrollViewer(DependencyObject element)
        {
            if (element is ScrollViewer)
            {
                return (ScrollViewer)element;
            }
    
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
            {
                var child = VisualTreeHelper.GetChild(element, i);
    
                var result = GetScrollViewer(child);
                if (result == null)
                {
                    continue;
                }
                else
                {
                    return result;
                }
            }
    
            return null;
        }
    

    credits to the owner of the code

提交回复
热议问题