ListView中的无限滚动

时间:2015-02-26 17:03:27

标签: windows-phone-8.1 winrt-xaml

我试图在列表视图中实现无限滚动。

方法是在listview中获取滚动条并将事件处理程序挂钩到它的滚动事件。

<CollectionViewSource x:Key="PaginatedData"
                      IsSourceGrouped="True"
                      ItemsPath="CommentaryList"
                      Source="{Binding paginatedCommentary}"/>

 <ListView x:Name="commentaryListView"
           Loaded="commentaryListView_Loaded"
           ItemTemplate="{StaticResource CommentaryListTemplate}"
           ItemsSource="{Binding Source={StaticResource PaginatedData}}"/>
private void commentaryListView_Loaded(object sender, RoutedEventArgs e)
{
    var scrollViewer = commentaryListView.GetFirstDescendantOfType<ScrollViewer>();
    var scrollbars = new List<ScrollBar>(scrollViewer.GetDescendantsOfType<ScrollBar>());
    var verticalBar = scrollbars.FirstOrDefault(x => x.Orientation == Orientation.Vertical);
    if (verticalBar != null)
       verticalBar.Scroll += BarScroll; 

}

private void BarScroll(object sender, ScrollEventArgs e)
{
   if (e.ScrollEventType != ScrollEventType.EndScroll) return;

   var bar = sender as ScrollBar;
   if (bar == null) return;

   if (e.NewValue >= bar.Maximum)
   {
       datacontext.pageCommentaryItems();
   }
}

似乎无法弄清楚我在这里做了些什么,但它从来没有碰到过BarScroll事件处理程序。

感谢您的帮助。谢谢:))

2 个答案:

答案 0 :(得分:0)

我建议您直接使用ListView的 ViewChanged 事件:

    private void OnListViewLoaded(object sender, RoutedEventArgs e)
    {
        var listview = sender as ListViewBase;
        if (listview != null)
        {
              // Attach to the view changed event
            _scrollViewer = listview.GetFirstDescendantOfType<ScrollViewer>();
            if (_scrollViewer != null)
            {
                _scrollViewer.ViewChanged += OnViewChanged;
            }
        }
    }

    private void OnViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
    {
        // If scrollviewer is scrolled down at least 90%
        if (_scrollViewer.VerticalOffset > Math.Max(_scrollViewer.ScrollableHeight * 0.9, _scrollViewer.ScrollableHeight - 150))
        {
            // Execute whatever you want
        }
    }

答案 1 :(得分:0)

更简单的解决方案是创建一个可观察的集合,该集合实现ISupportIncrementalLoading接口并将其绑定到ListView。这将使ListView执行增量滚动而无需自己实现它。见https://marcominerva.wordpress.com/2013/05/22/implementing-the-isupportincrementalloading-interface-in-a-window-store-app/