WinRT 自带 ISupportIncrementalLoading接口使用

在Win10的Metro应用上,MS引入了一自动加载的数据源接口ISupportIncrementalLoading

ISupportIncrementalLoading实现以下

bool HasMoreItems { get; }

IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count);

 其中,后者方法为异步加载数据。通过MSDN的例子.

1.实现一个数据源接口,让我们得以源源不断从这里取得数据,一般的数据接口都采用分页,偏差来设定。

    /// <summary>
        /// 数据源接口
        /// </summary>
        /// <param name="query">查询语句</param>
        /// <param name="pageIndex">页面索引</param>
        /// <param name="pageSize">分页大小</param>
        /// <returns></returns>
        Task<IEnumerable<T>> GetPagedItems(string query,int pageIndex, int pageSize);        

 2.一个实现了以上两个接口的类

public class IncrementalLoadingCollection<T, I> : ObservableCollection<I>,
         ISupportIncrementalLoading
         where T : IIncrementalSource<I>

 3.分别实现各个接口的方法

     private T source;
        private int pageSize;
        private bool hasMoreItems;
        private int currentPage;
        private string query;

        public IncrementalLoadingCollection(string query,int pageSize )
        {
            this.source = new T();
            this.pageSize = pageSize;
            this.hasMoreItems = true;
            this.query = query;
        }

        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(query,currentPage++, pageSize);

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

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

                        if (resultCount < pageSize)
                        {
                            hasMoreItems = false;
                        }
                    }

                    Debug.WriteLine("Already Loading count{0},Everytime loading count:{1}",this.Items.Count, count);
                    return new LoadMoreItemsResult() { Count = resultCount };

                }).AsAsyncOperation<LoadMoreItemsResult>();

 其中对于hasMoreItems的判断,要考虑没有取到列表以及取到列表还要比较取到的列表个数,是不是比pagSize小的问题(最后一页可能这样)

4.产生IncrementalLoadingCollection的子类,其中要具体实现GetPagedItems方法。

    public class PostSource : IIncrementalSource<PostDetail>
    {


     
        public async Task<IEnumerable<PostDetail>> GetPagedItems(string query,int pageIndex, int pageSize)
        {
            //if (pageIndex < 1)
            //    throw new ArgumentOutOfRangeException("pageIndex");
            //if (pageSize < 1)
            //    throw new ArgumentOutOfRangeException("pageSize");

            var jsontext = await HttpHelper.GetTextByPost(Strings.PostListUri, query,
                new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("sa", query),
                    new KeyValuePair<string, string>("offset", (pageIndex*pageSize).ToString()),
                    new KeyValuePair<string, string>("count", pageSize.ToString()),
                    new KeyValuePair<string, string>("uid", "13916551"),
                    new KeyValuePair<string, string>("platform", "a"),
                    new KeyValuePair<string, string>("mobile", "Emnu"),

                });

            if (jsontext!=null)
            {
                JObject postlist = JObject.Parse(jsontext);
                var list = postlist.SelectToken("list").Select(item => new PostDetail()
                {
                    Title = (string) item["title"],
                    Des = (string) item["des"],
                    Creattime = (string) item["adddate"],
                    Icon = new Uri(Strings.HostUri + (string) item["icon"]),
                    Id = Convert.ToInt32((string) item["id"]),
                    PostUrl =
                        string.Format(
                            "{0}",
                            Convert.ToInt32((string) item["id"])),
                });
                return list;
            }


            return null;
            
        }
    }

 5.的页面Binding这个类的实例即可

new IncrementalLoadingCollection<PostSource, PostDetail>("查询语句", 20);

 

 

 

 

 

posted on 2015-09-13 17:29  HelyCheng  阅读(304)  评论(0)    收藏  举报

导航