2014-01-18 47 views
1

當用戶觸摸應用程序圖標, 我想要做這些步驟用戶之前去主視圖準備數據之前去主視圖

  1. 從URI
  2. 使用JArray.Parse獲取JSON字符串獲取值
  3. 完成後,轉到主視圖。

問題是我如何阻止用戶去主視圖 ,並把所有
我試圖把它在App.xaml.cs Application_Launching方法的代碼文件

// Code to execute when the application is launching (eg, from Start) 
// This code will not execute when the application is reactivated 
private void Application_Launching(object sender, LaunchingEventArgs e) 
{ 
    // code here 
} 

但是它並不妨礙程序在抓取完成之前轉到主視圖。
而且我發現,其實在MainPage.xaml中,如果我把這個代碼這樣

protected override void OnNavigatedTo(NavigationEventArgs e) 
{ 
    while(true) {} 
    // it will prevent the program to go to the main view, 
    // and will stick with the loading screen until this function reach its end 
} 

所以我想,我可以在這裏把所有的代碼,當我完成抓取,我剛剛突破這時,它會自動轉到主視圖。

我試試,這是代碼

protected override void OnNavigatedTo(NavigationEventArgs e) 
{ 
    bool isFetchFinished = false; 

    ObservableCollection<PromoViewModel> Promos = new ObservableCollection<PromoViewModel>(); 

    WebClient client = new WebClient(); 

    client.DownloadStringCompleted += (s, evt) => 
    { 
     if (evt.Error == null) 
     { 
      // Retrieve the JSON 
      string jsonString = evt.Result; 

      JArray promos = JArray.Parse(jsonString); 
      foreach (JObject promo in promos) 
      { 
       string name = promo["name"].Value<string>(); 
       string description = promo["description"].Value<string>(); 
       string img = promo["image"].Value<string>(); 

       Promos.Add(new PromoViewModel() { Name = name, Description = description, Img = img }); 
      } 
      isFetchFinished = true; 
      System.Diagnostics.Debug.WriteLine("finish fetch"); 
     } 
    }; 

    // run 
    client.DownloadStringAsync(new Uri("the json url")); 

    while(true) { 
     if(isFetchFinished) { 
      App.ViewModel.LoadData(Promos); // pass value to main view model 
      break; // after complete, break 
     } 
    } 
} 

我認爲這是可行的,但事實並非如此。
這就是我發現的,
WebClient DownloadStringAsync在OnNavigatedTo函數完成之前不會運行。
因爲它仍在等待while循環中斷並達到最終功能。

isFetchFinished = true; // will never executed 

得到的無限循環。
我想我把錯誤的方法提取代碼。在哪裏放置所有這些?

回答

3

哎喲,你這樣做都是錯誤的。首先,你必須指定起始頁面。如果您想在導航到它之前下載一些數據,您可以創建一個特殊的「下載」頁面,該頁面實際上是啓動應用程序時導航到的第一個頁面。然後,一旦下載完成,您將導航到您的主頁面。這實際上是擴展閃屏的替代品。

另外,從來沒有把while (true)放在任何UI代碼中,這將簡單地凍結應用程序。此外,如果應用程序被凍結,你永遠不會有機會「解凍」它。

+0

感謝兄弟,我來自iOS世界,所以這是iOS的方式來做到這一點。 我不知道在windows phone中,要下載數據我們必須創建一個新的視圖。 你能告訴我一點點語法嗎? –

+0

我並沒有說你*需要*來創建一個新的視圖,我說你*可以*創建一個不同的起始頁面 - 一個會顯示一些「正在下載...」文本,直到數據完成下載,然後自動獲取用戶到實際的起始頁面。 –