2011-07-11 38 views
0

我有下面的代碼,如果你只是想用Bing地圖的響應來填充一個圖片,那麼這個代碼工作正常。但如果我嘗試做兩個,那麼變量_currentImage總是以「image1」結尾,因爲這些調用是異步的。我如何將Image變量傳遞給ImageryServiceGetMapUriCompleted方法?如何從Bing Maps異步調用填充多個Silverlight圖像?

using System; 
using System.Windows.Controls; 
using System.Windows.Media.Imaging; 
using BasicBingMapsImagerySvc.ImageryService; 

namespace BasicBingMapsImagerySvc 
{ 
    public partial class MainPage : UserControl 
    { 
     private const string BingMapsKey = "my key"; 

     private Image _currentImage; 

     public MainPage() 
     { 
      InitializeComponent(); 

      GetMap(42.573377, -101.032251, image0, MapStyle.AerialWithLabels); 

      GetMap(42.573377, -101.032251, image1, MapStyle.Road_v1); 
     } 


     private void GetMap(double lat, double lon, Image image, MapStyle mapStyle) 
     { 
      var mapUriRequest = new MapUriRequest(); 

      // Set credentials using a valid Bing Maps key 
      mapUriRequest.Credentials = new Credentials(); 
      mapUriRequest.Credentials.ApplicationId = BingMapsKey; 

      // Set the location of the requested image 
      mapUriRequest.Center = new Location(); 
      mapUriRequest.Center.Latitude = lat; 
      mapUriRequest.Center.Longitude = lon; 

      // Set the map style and zoom level 
      var mapUriOptions = new MapUriOptions(); 
      mapUriOptions.Style = mapStyle; 
      mapUriOptions.ZoomLevel = 13; 

      // Set the size of the requested image to match the size of the image control 
      mapUriOptions.ImageSize = new SizeOfint(); 
      mapUriOptions.ImageSize.Height = 256; 
      mapUriOptions.ImageSize.Width = 256; 

      mapUriRequest.Options = mapUriOptions; 

      var imageryService = new ImageryServiceClient("BasicHttpBinding_IImageryService"); 
      imageryService.GetMapUriCompleted += ImageryServiceGetMapUriCompleted; 

      _currentImage = image; 

      imageryService.GetMapUriAsync(mapUriRequest); 


     } 

     private void ImageryServiceGetMapUriCompleted(object sender, GetMapUriCompletedEventArgs e) 
     { 
      // The result is an MapUriResponse Object 
      MapUriResponse mapUriResponse = e.Result; 
      var bmpImg = new BitmapImage(new Uri(mapUriResponse.Uri)); 

      _currentImage.Source = bmpImg; 
     } 
    } 
} 

回答

1

你可以使用lambda表達式/委託事件處理程序,它允許您「捕獲」的參考圖像:

var imageryService = new ImageryServiceClient("BasicHttpBinding_IImageryService"); 
    imageryService.GetMapUriCompleted += (s,e) => 
    { 
     // The result is an MapUriResponse Object 
     MapUriResponse mapUriResponse = e.Result; 
     var bmpImg = new BitmapImage(new Uri(mapUriResponse.Uri)); 

     // set the image source 
     image.Source = bmpImg; 
    }; 
+0

科林,你真棒!謝謝。我試圖自己去那裏,但無法弄清楚lambda語法。 – Stonetip