Windows Phone,在异步回调上设置图像源不起作用?

时间:2012-08-07 22:27:11

标签: image asynchronous windows-phone

我从Bing获取图像以显示在我的应用中。我按照Bing的说明,成功检索了图像的URL,但由于某种原因,模拟器不会显示它们!这就是我所拥有的

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]));

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

2 个答案:

答案 0 :(得分: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])); 
        });

现在有效!

答案 1 :(得分:0)

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

此外,调试器停止时会出现什么异常?