2012-04-28 74 views
0

今天我遇到了這個「有趣」的問題。 我在一個wpf窗口上有一個按鈕,當我按下它時,我想要一個矩形變爲可見並展開到我的主窗口的大小。然後將文本保存在矩形內部以對齊它的中心。發生這種情況後,我希望腳本從網上下載圖像以開始執行。不過......當我按下按鈕,我的矩形不會成爲可見,取而代之的是exe文件開始下載圖像...我想代碼應該按順序執行...在預定腳本之前執行映像下載

On button_1 press(blah blah){ 

expander1.IsExpanded = false; //just an expander i use to hide a few elements 

      pleasewait.Visibility = Visibility.Visible; //pleasewait - rectangle 
      plswait_label.Visibility = Visibility.Visible; // plswait_lable - label 
      pleasewait.Height = window_main.Height; 
      pleasewait.Width = window_main.Width; 
      plswait_label.HorizontalAlignment = HorizontalAlignment.Center; 
      plswait_label.VerticalAlignment = VerticalAlignment.Center; 

      image1.Source = null; // dumping previous image before downloading a new one 



//This is the script to download the image and do some other stuff.. 
    string path = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); 

    Uri urlUri = new Uri(address.Text); 
    var request = WebRequest.CreateDefault(urlUri); 

    byte[] buffer = new byte[4096]; 

    using (var target = new FileStream(path + @"\Temp\br_temp.png", FileMode.Create, FileAccess.Write)) 
    { 
     using (var response = request.GetResponse()) 
     { 
      using (var stream = response.GetResponseStream()) 
      { 
       int read; 

       while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) 
       { 
        target.Write(buffer, 0, read); 
       } 
      } 
     } 
    } 


    Bitmap resizedImage; 
    System.Drawing.Size newSize = new System.Drawing.Size(266, 150); 

    using (System.Drawing.Image originalImage = System.Drawing.Image.FromFile(path + @"\Temp\br_temp.png")) 
     resizedImage = new System.Drawing.Bitmap(originalImage, newSize); 
    resizedImage.Save(path + @"\Temp\temp.png", System.Drawing.Imaging.ImageFormat.Jpeg); 
    resizedImage.Dispose(); 

    BitmapImage MainImage = new BitmapImage(); 
    MainImage.BeginInit(); 
    MainImage.UriSource = new Uri(path + @"\Temp\temp.png"); 
    MainImage.DecodePixelWidth = 266; 
    MainImage.DecodePixelHeight = 150; 
    MainImage.EndInit(); 
    image1.Source = MainImage; 
} 

滑稽的是,如果我刪除下載代碼,矩形實際上做我想要它..

回答

1

下載阻止了UI線程。在下載完成之前,UI上的任何內容都不會起作用。

您需要將下載代碼從UI線程中移出。

一個簡單的方法做,這是一個BackgroundWorker

像往常一樣,我建議你閱讀Joe Albahari's ebook