为了在我的 WP8.1 通用应用程序中进行无休止的滚动,我实现了 ISupportIncrementalLoading,并使用结果绑定到我的 ListView。使用此代码可以正常工作:
public sealed class IncrementalLoadingCollection<T, I> : ObservableCollection<I>, ISupportIncrementalLoading
where T : IIncrementalSource<I>, new()
{
private int currentPage;
private bool hasMoreItems;
private int itemsPerPage;
private T source;
public IncrementalLoadingCollection(int itemsPerPage = 10)
{
this.source = new T();
this.itemsPerPage = itemsPerPage;
this.hasMoreItems = true;
}
public bool HasMoreItems
{
get { return this.hasMoreItems; }
}
public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
{
return AsyncInfo.Run(c => LoadMoreItemsAsync(c, count));
}
private async Task<LoadMoreItemsResult> LoadMoreItemsAsync(CancellationToken cancellationToken, uint count)
{
var dispatcher = Window.Current.Dispatcher;
var task = await Task.Run<LoadMoreItemsResult>(
async () =>
{
if (Count == 0 && this.currentPage > 0)
{
this.currentPage = 0; // this was cleared
}
uint resultCount = 0;
var result = await this.source.GetPagedItems(cancellationToken, this.currentPage, this.itemsPerPage);
this.currentPage++;
if (result == null || !result.Any())
{
this.hasMoreItems = false;
}
else
{
resultCount = (uint)result.Count();
await dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
() =>
{
foreach (I item in result)
{
Add(item);
}
});
}
return new LoadMoreItemsResult { Count = resultCount };
}, cancellationToken);
return task;
}
}
现在我正在尝试使用以下代码清除所有加载的项目并从不同的 url 加载新数据(用户应该能够切换“类别”):
public void ClearAndSetNewUrl(string newUrl)
{
if (this.LoadMoreItemsAsync((uint) this.itemsPerPage).Status == AsyncStatus.Started)
{
this.LoadMoreItemsAsync((uint) this.itemsPerPage).Cancel();
}
this.source.SetUrl(newUrl);
this.hasMoreItems = true;
base.ClearItems();
}
但结果通常填充来自旧 url 的结果(可能是因为异步查询)或 hasMoreItems 设置为 false 和/或增量加载停止工作。
摆脱所有以前的项目,停止从旧网址加载的所有任务并仅从新网址开始加载的正确方法是什么?