2012-08-07 23 views
1

我从Bing获取图像以显示在我的应用程序中。我遵循Bing的指示,我成功地检索了图像的URL,但出于某种原因,模拟器不会显示它们!下面是我有Windows Phone,在异步回调上设置图像源不起作用?

var bingContainer = new Bing.BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/Search/")); 

      var accountKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"; 
      bingContainer.Credentials = new NetworkCredential(accountKey, accountKey); 

      var imageQuery = bingContainer.Image("porsche", null, null, null, null, null, "Size:Medium"); 

      imageQuery.BeginExecute(new AsyncCallback(this.ImageResultLoadedCallback), imageQuery); 

然后,我让我的图片,并尝试在这里设置:

var imageQuery = (DataServiceQuery<Bing.ImageResult>)ar.AsyncState; 

     var enumerableImages = imageQuery.EndExecute(ar); 
     var imagesList = enumerableImages.ToList(); 

     List<String> imList = new List<String>(); 

     while (imList.Count != 3) 
     { 
      Bing.ImageResult tr = imagesList.First<Bing.ImageResult>(); 
      if (tr.ContentType == "image/jpeg") 
      { 
       imList.Add(tr.MediaUrl); 
      } 
      imagesList.RemoveAt(0); 
     } 

     image1.Source = new BitmapImage(new Uri(@imList[0])); 
     image2.Source = new BitmapImage(new Uri(@imList[1])); 
     image3.Source = new BitmapImage(new Uri(@imList[2])); 

当我调试,过程似乎只停留在哪里设置的最后三个行资源。

回答

0

您确定MediaUrl正在将图片返回到正确的网址吗?如果你使用一些硬编码的URL到imList列表中的图像,图像会在image1,image2和image3中正确加载吗?我要说的是,也许数据的质量是不正确的。也就是说,尽管您的查询执行得很好,但MediaURL不包含格式正确的URL。

此外,当调试器停止时会发生什么异常?

1

好的,经过两天的挫折,我发现你不能从异步回调访问UI线程。 VS没有给出任何错误,但图像没有显示。异步回调与主UI线程一起运行,因此无法访问或更改UI中的元素。简单的解决方法只是涉及包装访问的UI这样的代码行:

Dispatcher.BeginInvoke(() => 
     { 
      image1.Source = new BitmapImage(new Uri(@imList[0])); 
      image2.Source = new BitmapImage(new Uri(@imList[1])); 
      image3.Source = new BitmapImage(new Uri(@imList[2])); 
     }); 

它现在!