private void Worker_DoWork(object sender, DoWorkEventArgs e) { try { using (WebClient client = new WebClient() { CachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable) }) { ImageLoaderOptions options = e.Argument as ImageLoaderOptions; BitmapImage bmp = new BitmapImage(); bmp.BeginInit(); bmp.StreamSource = new MemoryStream(client.DownloadData(options.Uri)); bmp.CacheOption = BitmapCacheOption.OnLoad; if (options.DecodePixelWidth != -1) { bmp.DecodePixelWidth = options.DecodePixelWidth; } bmp.EndInit(); bmp.Freeze(); e.Result = bmp; } } catch { e.Result = null; } }
/// <summary> /// Updates the UriSource. /// </summary> /// <param name="oldValue">The old value.</param> private void UpdateUriSource(Uri oldValue) { if (_image == null || !IsLoaded) { return; } if (DesignerProperties.GetIsInDesignMode(this)) { _image.Opacity = 1; return; } if (oldValue != null && UriSource != null && oldValue.OriginalString == UriSource.OriginalString) { return; } IsImageLoading = true; _image.Source = null; if (UriSource == null) { return; } if (_worker != null) { _worker.DoWork -= Worker_DoWork; _worker.RunWorkerCompleted -= Worker_RunWorkerCompleted; } _worker = new BackgroundWorker(); _worker.DoWork += Worker_DoWork; _worker.RunWorkerCompleted += Worker_RunWorkerCompleted; ImageLoaderOptions options = new ImageLoaderOptions { Uri = UriSource, DecodePixelWidth = -1 }; if (RenderAtSize) { UpdateLayout(); options.DecodePixelWidth = (int)Math.Max(ActualWidth, ActualHeight); } _worker.RunWorkerAsync(options); }