Windows 8 应用程序分组项目页 - 添加项目



我正在使用基于Visual Studio模板的GroupedItemsPage。提供了一个 SampleDataSource,因此我以它为例并创建了自己的数据源。但是,我想将异步下载的项目添加到网格视图中。问题是,一旦我返回结果并处理它们并将它们添加到数据源,屏幕就不会更新以显示新的网格页。

这是我在 GroupedItemsPage 类上的LoadState方法:

protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            // TODO: Create an appropriate data model for your problem domain to replace the sample data
            var h = DataModel.MainPageDataSource.GetSingleton().GetGridGroups("AllGroups");
            this.DefaultViewModel["Groups"] = h;
        }

这是我的数据源类:

class MainPageDataSource : FacepunchWin8.Common.BindableBase
    {
        public static MainPageDataSource _singleton = new MainPageDataSource();
        public static MainPageDataSource GetSingleton() { return _singleton; }
        private static Uri _baseUri = new Uri("ms-appx:///");
        private ObservableCollection<MainPageGrid> _gridGroups = new ObservableCollection<MainPageGrid>();


        void IndexParserComplete(HTMLParser p)
        {
            HTMLParserIndex parser = p as HTMLParserIndex;
            foreach (ForumSection f in parser.GetForumSections())
            {
                MainPageGrid forumGrid = new MainPageGrid(f.Title(), f.Title());
                _gridGroups.Add(forumGrid);
            }

        }
        private void ItemsCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
        }
        public MainPageDataSource()
        {
            HTMLParserIndex parser = new HTMLParserIndex();
            parser.SetComplateDelegate(IndexParserComplete);
            Scraper.GetSingleton().RequestForumIndex(parser);
            MainPageGrid Grid1 = new MainPageGrid("GRID1", "TestPage");
            Grid1.Items.Add(new MainPageGridItem("Grid00", "GridOne", "Subtitle", "Assets/DarkGray.png"));
            _gridGroups.Add(Grid1);

        }
        public ObservableCollection<MainPageGrid> GetGridGroups(string uniqueId)
        {
            if (!uniqueId.Equals("AllGroups")) throw new ArgumentException("Only 'AllGroups' is supported as a collection of groups");
            return _gridGroups;
        }

    }

构造函数创建一些与SampleDataSource非常相似的项,这些项在屏幕上正确显示。但是,从互联网下载数据后,调用IndexParserComplete,这会为_gridGroups添加一些新项目。如何通知分组项页刷新屏幕并从数据源重新读取数据?

我终于找到了答案。事实证明,不支持从另一个线程修改可观察集合/从另一个线程设置数据源。由于我正在从异步操作添加数据,因此我需要使用调度程序通过主 UI 线程添加数据。

_gridGroups.Add(forumGrid);IndexParserComplete(HTMLParser p)中,我替换为:

 this._uiDispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
               {
                    DataModel.MainPageDataSource.GetSingleton().AddPageGrid(forumGrid);
               })

其中 _uiDispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher ;

最新更新