介紹
重新想象 Windows 8 Store Apps 之 綁定
通過實現 ISupportIncrementalLoading 介面,為 ListViewBase 的增量載入提供資料
樣本
實現 ISupportIncrementalLoading 介面,以便為 ListViewBase 的增量載入提供資料
Binding/MyIncrementalLoading.cs
/* * 示範如何? ISupportIncrementalLoading 介面,以便為 ListViewBase 的增量載入提供資料 * * ISupportIncrementalLoading - 用於支援增量載入 * HasMoreItems - 是否還有更多的資料 * IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count) - 非同步載入指定數量的資料(增量載入) * * LoadMoreItemsResult - 增量載入的結果 * Count - 實際已載入的資料量 */ using System;using System.Collections.Generic;using System.Collections.ObjectModel;using System.Runtime.InteropServices.WindowsRuntime;using System.Threading.Tasks;using Windows.Foundation;using Windows.UI.Core;using Windows.UI.Xaml;using Windows.UI.Xaml.Data; namespace XamlDemo.Binding{ public class MyIncrementalLoading<T> : ObservableCollection<T>, ISupportIncrementalLoading { // 是否正在非同步載入中 private bool _isBusy = false; // 提供資料的 Func // 第一個參數:增量載入的起始索引;第二個參數:需要擷取的資料量;第三個參數:擷取到的資料集合 private Func<int, int, List<T>> _funcGetData; // 最大可顯示的資料量 private uint _totalCount = 0; /// <summary> /// 建構函式 /// </summary> /// <param name="totalCount">最大可顯示的資料量</param> /// <param name="getDataFunc">提供資料的 Func</param> public MyIncrementalLoading(uint totalCount, Func<int, int, List<T>> getDataFunc) { _funcGetData = getDataFunc; _totalCount = totalCount; } /// <summary> /// 是否還有更多的資料 /// </summary> public bool HasMoreItems { get { return this.Count < _totalCount; } } /// <summary> /// 非同步載入資料(增量載入) /// </summary> /// <param name="count">需要載入的資料量</param> /// <returns></returns> public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count) { if (_isBusy) { throw new InvalidOperationException("忙著呢,先不搭理你"); } _isBusy = true; var dispatcher = Window.Current.Dispatcher; return AsyncInfo.Run( (token) => Task.Run<LoadMoreItemsResult>( async () => { try { // 類比長時任務 await Task.Delay(1000); // 增量載入的起始索引 var startIndex = this.Count; await dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { // 通過 Func 擷取增量資料 var items = _funcGetData(startIndex, (int)count); foreach (var item in items) { this.Add(item); } }); // Count - 實際已載入的資料量 return new LoadMoreItemsResult { Count = (uint)this.Count }; } finally { _isBusy = false; } }, token)); } }}