2014-06-08 170 views
1

我有一种方法是下载XML并将其数据分类到collectionA。然后我将collectionA拆分为2个较小的集合,collectionB & collectionC其中填充了2个列表。现在我遇到的问题是填充和拆分collectionA的方法正在完成之前,collectionA有时间填充本身。加载页面后的加载方法

我该如何去制作collectionB & collectionC等到collectionA被填充?

方法填充collectionA

public void downloadXML(bool data) 
      { 
       if (data == false) 
       { 
        WebClient wc = new WebClient(); 
        wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted); 
        wc.DownloadStringAsync(new Uri("http://ec.urbentom.co.uk/studentAppData.xml")); 
       }    
      } 

      private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
      { 
       setupDictionary(); 
       MainPage page = new MainPage(); 
       if (e.Error != null) 
        return; 
       XElement xmlitems = XElement.Parse(e.Result); 
       List<XElement> elements = xmlitems.Descendants("item").ToList(); 

       List<StudentGuideModel> moveItems = new List<StudentGuideModel>(); 
       foreach (XElement c in elements) 
       { 
        StudentGuideModel _item = new StudentGuideModel(); 

        _item.Title = c.Element("Title").Value; 
        _item.Description = c.Element("Description").Value; 
        _item.Phone = c.Element("Phone").Value; 
        _item.Email = c.Element("Email").Value; 
        _item.Category = c.Element("Category").Value; 
        _item.Image = c.Element("Image").Value; 
        _item.SmallInfo = c.Element("SmallInfo").Value; 
        _item.Image = getImage(_item.Image); 
        allData.Add(_item); 
       } 
       MessageBox.Show("Download Complete", "Loaded", MessageBoxButton.OK);               
      } 

方法填充collectionB & collectionC

public ObservableCollection<StudentGuideModel> splitCategories(string catName) 
{ 
    ObservableCollection<StudentGuideModel> catItems = new ObservableCollection<StudentGuideModel>(); 
    foreach (var item in allData) 
    { 
     if (item.Category == catName) 
     { 
      catItems.Add(item); 
     } 
    } 
    return catItems; 
} 

名单的人口使用collectionB & collectionC

faciliiesList.ItemsSource = App.getControl.splitCategories("Facilities"); 
contactPanel.ItemsSource = App.getControl.splitCategories("Contacts"); 
+0

请添加调用b和c的tge填充的代码,这样我们就可以看到为什么在完成填充之前完成填充 –

回答

0

我假设你先调用downloadXML,然后在page_Loaded事件处理程序中调用splitCategories。 (顺便说一句,你应该遵循C#命名约定,你的方法应该是DownloadXML和SplitCategories)。

因为您的webclient订阅了DownloadStringCompleted事件,您的splitCategories可能会在下载字符串之前开始填充B和C.我建议你从NuGet获得HTTP客户端库(Microsoft.Net.Http是NuGet上的id)。 HTTPClient使用异步/等待框架,它会为你完成这项工作。以下是示例代码:

HttpClient client = new HttpClient(); 
client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow; 
string downloadedString = await client.GetStringAsync("http://ec.urbentom.co.uk/studentAppData.xml"); 
// Populate A here 
// PopulateB here 

请注意,您必须将async关键字添加到Loaded事件处理程序。