Image img = new Image {HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = System.Windows.VerticalAlignment.Stretch}; ThreadStart thread = delegate { BitmapImage bmpImage = new BitmapImage(); MemoryStream ms = new MemoryStream(); FileStream fs = File.Open(@"C:\ImageFileName.jpg", FileMode.Open); MediaCoder.MediaDecoder.DecodeMediaWithStream(ImageItem, true, ms); bmpImage.BeginInit(); bmpImage.StreamSource = ms; bmpImage.EndInit(); bmpImage.Freeze(); Dispatcher.BeginInvoke(new ThreadStart(delegate { img.Source = bmpImage; img.Unloaded += delegate { ms.Close(); ms.Dispose(); }; grdImageContainer.Children.Add(img); })); }; new Thread(thread).Start();
直接重新赋值一次就替换了。
这是一个完整的例子:
private void button1_Click(object sender, RoutedEventArgs e) { ThreadPool.QueueUserWorkItem(LoadImage, new LoadImageRequest { ImageName = "Image.png", Control = image1 }); } private void LoadImage(object state) { var request = (LoadImageRequest)state; byte[] data = ...; // load bytes from the database using request.ImageName using (var stream = new MemoryStream(data)) { var imageSource = BitmapFrame.Create(stream); Dispatcher.BeginInvoke( new Action<ImageSource>(p => request.Control.Source = p), imageSource ); } } private class LoadImageRequest { public string ImageName; public Image Control; }