如何以简单的方式为UWP实现延迟加载ListView?

时间:2016-05-07 12:40:26

标签: listview win-universal-app loading lazy-evaluation

我在网上看过样本,有些很难学。

我想学习如何理解ListView向下滚动的时间以及是否还有更多数据,如何在屏幕上显示ProgressRing时从互联网上获取数据。

对于我的示例,我使用JSON从PHP服务器获取数据,并且每个请求都从数据库中获取10个项目。

如果您能提供易于理解的样品,我们将非常感激。

3 个答案:

答案 0 :(得分:1)

我找到了一种使用ISupportIncrementalLoading接口加载数据的方法,我的问题是如何告诉listview每页每10项。

怎么说下载下一部分

这是我课堂上的代码。

structList是对象的类模型。

  public sealed partial class MainPage : Page
    {
        public string category;

        public MainPage()
        {
            this.InitializeComponent();
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
         
            myListView.ItemsSource = new ItemsDataSource();
        }  


	}


  class ItemsDataSource : ObservableCollection<StructList>, ISupportIncrementalLoading
    {
        public int lastItem = 0;
		public string part =0;
    

        public bool HasMoreItems
        {
            get
            {
                if (lastItem == 10000)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }

        public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
        {


            CoreDispatcher coreDispatcher = Window.Current.Dispatcher;

            return Task.Run<LoadMoreItemsResult>(async () =>
            {
                await coreDispatcher.RunAsync(CoreDispatcherPriority.Normal,
                    () =>
                    {
                   
                    });

					
		   //get data by part 
		   //part in my server start with 0 and later 1,2,3...
		    List<StructList> items = new List<StructList>();
                    List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();
                    postData.Add(new KeyValuePair<string, string>("part", part));
                    string JSonData = await WebService.get_post_respone(url, postData);
                    items = JsonConvert.DeserializeObject<List<StructList>>(JSonData);
                   
                
                await coreDispatcher.RunAsync(CoreDispatcherPriority.Normal,
                    () =>
                    {
                        foreach (StructList item in items)
                        {
                            this.Add(item);
                        }
                    });

                return new LoadMoreItemsResult() { Count =count };
            }).AsAsyncOperation<LoadMoreItemsResult>();
        }
    }

答案 1 :(得分:1)

public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            myListView.ItemsSource = new ItemsDataSource();
        }
    }
    public interface IIncrementalSource<T>
    {
        Task<IEnumerable<T>> GetPagedItems(int pageIndex, int pageSize,string url);
    }

    public class IncrementalLoadingCollection<T, I> : ObservableCollection<I>,
         ISupportIncrementalLoading
         where T : IIncrementalSource<I>, new()
    {
        private T source;
        private int itemsPerPage;
        private bool hasMoreItems;
        private int currentPage=0;
        string url;
        public IncrementalLoadingCollection(string url,int itemsPerPage = 10)
        {
            this.source = new T();
            this.itemsPerPage = itemsPerPage;
            this.hasMoreItems = true;
            this.url = url;
        }

        public bool HasMoreItems
        {
            get { return hasMoreItems; }
        }

        public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
        {
            var dispatcher = Window.Current.Dispatcher;

            return Task.Run<LoadMoreItemsResult>(
                async () =>
                {
                    uint resultCount = 0;
                    var result = await source.GetPagedItems(currentPage++, itemsPerPage,url);

                    if (result == null || result.Count() == 0)
                    {
                        hasMoreItems = false;
                    }
                    else
                    {
                        resultCount = (uint)result.Count();

                        await dispatcher.RunAsync(
                            CoreDispatcherPriority.Normal,
                            () =>
                            {
                                foreach (I item in result)
                                    this.Add(item);
                            });
                    }

                    return new LoadMoreItemsResult() { Count = resultCount };

                }).AsAsyncOperation<LoadMoreItemsResult>();
        }
    }
    public class StructList
    {
        public string Name { get; set; }
    }
    public class ItemsDataSource : IIncrementalSource<StructList>
    {
        private List<StructList> persons;

        public ItemsDataSource()
        {
            persons = new List<StructList>();

            //for (int i = 0; i < 1024; i++)
           // {
            //    var p = new StructList { Name = "Person " + i };
           //     persons.Add(p);
           // }
        }

        public async Task<IEnumerable<StructList>> GetPagedItems(int pageIndex, int pageSize,string url)
        {

            if (persons.Count > 10000) //you wriiten   if (lastItem == 10000),assuming max items 10000
                return null;
            //If you want only 10 items and url returns more than 10 at a time     
            var result = (from p in persons
                          select p).Skip(pageIndex * pageSize).Take(pageSize);
            if (result == null)
            {
                List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();
                postData.Add(new KeyValuePair<string, string>("part", pageIndex.ToString()));
                string JSonData = await WebService.get_post_respone(url, postData);
                var items = JsonConvert.DeserializeObject<List<StructList>>(JSonData);
                foreach (var item in items)
                    persons.Add(item);

                return await Task.Run<IEnumerable<StructList>>(() =>
                {
                    result = (from p in persons
                              select p).Skip(pageIndex * pageSize).Take(pageSize);

                    return result;
                });
            }
            else
                return result;
        }
    }

了解更多信息Refer this Link

答案 2 :(得分:0)

您可以使用

    <ScrollViewer x:Name="scrollViewer"
                 Loaded="scrollViewer_Loaded"
                  ViewChanged="scrollViewer_ViewChanged">

        <StackPanel Orientation="Vertical">
            <ProgressRing IsActive="{x:Bind IsPullRefresh,Mode=OneWay}" Height="30"></ProgressRing>
            <ListView x:Name="list" ItemsSource="{x:Bind Items}" ></ListView>
        </StackPanel>

    </ScrollViewer>
</Grid>



public sealed partial class MainPage : Page, INotifyPropertyChanged
{
    public ObservableCollection<object> Items { get; set; }

    public bool IsPullRefresh
    {
        get
        {
            return _isPullRefresh;
        }

        set
        {
            _isPullRefresh = value;
            OnPropertyChanged(nameof(IsPullRefresh));
        }
    }

    bool _isPullRefresh = false;

    public MainPage()
    {
        this.InitializeComponent();

        Items = new ObservableCollection<object>();
        for (int i = 0; i < 40; i++)
        {
            Items.Add(i);
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string name)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }

    private void scrollViewer_Loaded(object sender, RoutedEventArgs e)
    {
        scrollViewer.ChangeView(null, 30, null);
    }

    private async void scrollViewer_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
    {
        var sv = sender as ScrollViewer;

        if (!e.IsIntermediate)
        {
            if (sv.VerticalOffset == 0.0)
            {
                IsPullRefresh = true;
                await Task.Delay(2000);
                for (int i = 0; i < 5; i++)
                {
                    Items.Insert(0, i);
                }
                sv.ChangeView(null, 30, null);
            }
            IsPullRefresh = false;
        }
    }
}

如果你能看到中文,http://www.cnblogs.com/manupstairs/p/5184386.html