How do I get the start index and number of visible items in a ListView?

前端 未结 7 1965
迷失自我
迷失自我 2020-12-21 02:37

I have a listview working in virtual mode, in the LargeIcons view. Retrieves are expensive, so I want to ask for the data for all the visible items. How do I get the start

7条回答
  •  孤城傲影
    2020-12-21 03:12

    THE REAL Answer is :
    * get the ScrollViewer of the ListView.
    * ScrollViewer.VerticalOffset is the index of first shown item.
    * ScrollViewer.ViewportHeight is the number of items shown.

    To get the ScrollViewer, you will need a function, FindDescendant(FrameworkElement, Type) that will search within the childs of the ListView. Call it after Window was loaded.

    Code in VB.Net and in C# :

    Public Function FindDescendant(ByVal MyElementToSeek As FrameworkElement, _
                                      ByVal TypeToFind As Type) As FrameworkElement
        If MyElementToSeek Is Nothing Then Return Nothing
        If MyElementToSeek.GetType() = TypeToFind Then Return MyElementToSeek
        For i = 0 To VisualTreeHelper.GetChildrenCount(MyElementToSeek) - 1
            Dim OneChild = TryCast(VisualTreeHelper.GetChild(MyElementToSeek, i), FrameworkElement)
            Dim Result = FindDescendant(OneChild, TypeToFind)
            If Result IsNot Nothing Then Return Result
        Next
        Return Nothing
    End Function
    

    .

    public FrameworkElement FindDescendant(FrameworkElement MyElementToSeek, 
                                             Type TypeToFind) 
    {
        if (MyElementToSeek == null) return null;
        if (MyElementToSeek.GetType() == TypeToFind) return MyElementToSeek;
        for (i = 0; 
                   (i<= (VisualTreeHelper.GetChildrenCount(MyElementToSeek) - 1)); i++) 
          {
            object OneChild = TryCast(VisualTreeHelper.GetChild(MyElementToSeek, i),
                                                             FrameworkElement);
            object Result = FindDescendant(OneChild, TypeToFind);
            if (Result) return Result;
            }
         return null;
        }
    }
    
        ' MyScrollViewer = FindDescendant(MyListView, ScrollViewer)
    

提交回复
热议问题