當用戶觸摸應用程序圖標, 我想要做這些步驟用戶之前去主視圖準備數據之前去主視圖
- 從URI
- 使用JArray.Parse獲取JSON字符串獲取值
- 完成後,轉到主視圖。
問題是我如何阻止用戶去主視圖 ,並把所有
我試圖把它在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
得到的無限循環。
我想我把錯誤的方法提取代碼。在哪裏放置所有這些?
感謝兄弟,我來自iOS世界,所以這是iOS的方式來做到這一點。 我不知道在windows phone中,要下載數據我們必須創建一個新的視圖。 你能告訴我一點點語法嗎? –
我並沒有說你*需要*來創建一個新的視圖,我說你*可以*創建一個不同的起始頁面 - 一個會顯示一些「正在下載...」文本,直到數據完成下載,然後自動獲取用戶到實際的起始頁面。 –