1
我正在开发一个应用程序,并且遇到了异步调用的问题...以下是我正在尝试执行的操作。Windows Phone 7 - 等待Webclient完成
该应用程序使用JSON API,并在运行时使用必要的值(即单个新闻文章)填充全景项目中的列表框。当用户选择ListBox项目时,SelectionChanged事件被触发 - 它从选定的项目中拾取articleID,并将其传递给Update方法以下载文章的JSON响应,使用JSON.NET对其进行反序列化,用户转到WebBrowser控件,该控件根据收到的响应呈现html页面。
问题在于,我必须等待响应,然后再启动NavigationService,但我不确定如何正确执行此操作。这样,代码运行“太快”,我没有及时得到我的回应来呈现页面。
事件码:
private void lstNews_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lstNews.SelectedIndex == -1)
{
return;
}
ShowArticle _article = new ShowArticle();
ListBox lb = (ListBox)sender;
GetArticles item = (GetArticles)lb.SelectedItem;
string passId = ApiRepository.ApiEndpoints.GetArticleResponseByID(item.Id);
App.Current.JsonModel.JsonUri = passId;
App.Current.JsonModel.Update();
lstNews.SelectedIndex = -1;
NavigationService.Navigate(new Uri("/View.xaml?id=" + item.Id, UriKind.Relative));
}
的OnNavigatedTo方法在View:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
long sentString = long.Parse(NavigationContext.QueryString["id"]);
string articleUri = ApiRepository.ApiEndpoints.GetArticleResponseByID(Convert.ToInt32(sentString));
//this throws an error, runs "too fast"
_article = App.Current.JsonModel.ArticleItems[0];
}
的更新方法:
public void Update()
{
ShowArticle article = new ShowArticle();
try
{
webClient.DownloadStringCompleted += (p, q) =>
{
if (q.Error == null)
{
var deserialized = JsonConvert.DeserializeObject<ShowArticle>(q.Result);
_articleItems.Clear();
_articleItems.Add(deserialized);
}
};
}
catch (Exception ex)
{
//ignore this
}
webClient.DownloadStringAsync(new Uri(jsonUri));
}
谢谢!正是我需要它做的。 – zpodbojec
在这种情况下,如果它回答你的问题,请接受答案。 –