0

我今天遇到了这个“有趣”的问题。我在 wpf 窗口上有一个按钮,当我按下它时,我希望一个矩形变得可见并扩展到我的主窗口的大小。然后将文本保持在矩形内以在其中心对齐。发生这种情况后,我希望脚本从 Web 下载图像以开始执行。但是......当我按下按钮时,我的矩形不可见,而是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;
}

有趣的是,如果我删除下载代码,矩形实际上会做我想要的......

4

1 回答 1

1

下载阻塞了 UI 线程。在下载完成之前,UI 上的任何内容都不会起作用。

您需要将下载代码移出 UI 线程。

一个简单的方法是使用BackgroundWorker

一如既往,我推荐阅读Joe Albahari 的电子书

于 2012-04-28T14:53:08.827 回答