1

我已经实现了一个ISupportIncrementalLoading接口来执行ListView.

该接口有以下代码:

public interface IIncrementalSource<T>
    {
        Task<IEnumerable<T>> GetPagedItems(int pageIndex, int pageSize);
    }

    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;

        public IncrementalLoadingCollection(int itemsPerPage = 10)
        {
            this.source = new T();
            this.itemsPerPage = itemsPerPage;
            this.hasMoreItems = true;
        }

        public void UpdateItemsPerPage(int newItemsPerPage)
        {
            this.itemsPerPage = newItemsPerPage;
        }

        public bool HasMoreItems
        {
            get { return hasMoreItems; }
        }

        public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
        {

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

                    if(result == null || result.Count() == 0)
                    {
                        hasMoreItems = false;
                    } else
                    {
                        resultCount = (uint)result.Count();
                        await Task.WhenAll(Task.Delay(10), dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            foreach (I item in result)
                                this.Add(item);
                        }).AsTask());
                    }



                    return new LoadMoreItemsResult() { Count = resultCount };

                }).AsAsyncOperation<LoadMoreItemsResult>();
        }
    }

接口的实例是这个:

var collection = new IncrementalLoadingCollection<LiveTextCode, LiveText>();
this.LTextLW.ItemsSource = collection;

Where LiveTextis a UserFormandLiveTextCode是一个类,除其他功能外,它设置了前UserForm一个。

UserForm通过读取位于服务器中的 XML 文件来填充,因此代码必须执行async操作,为此,包含范围也必须是。由于未知原因,自定义接口的实例在填充之前被调用,所以,我得到了一个NullReferenceException(或者至少是对我最有意义的假设......)。

我很迷茫,我不知道如何解决它,如果有人可以帮助它,将不胜感激。

提前致谢!

4

1 回答 1

0

而不是使用this.LTextLW.ItemsSource = collection;
指定一个 ObservableCollection 项目说collection。现在通过将它绑定到您的ItemsSource="{Binding collection}".
由于它是 ObservableCollection 类型,因此一旦您的集合值更新,它也会反映在您的视图中。否则,您还可以使用Event
指定集合RaisePropertyChanged

private IncrementalLoadingCollection<LiveTextCode, LiveText> _collection;
public IncrementalLoadingCollection<LiveTextCode, LiveText> collection
        {
            get { return _collection; }
            set
            {
                _collection = value;
                RaisePropertyChanged();
            }
        }

这将在值更改时处理 UI 的更新。

于 2016-04-04T04:38:47.210 回答