C# WPF - Dynamically Loading Images Asynchronously Into a StackPanel From a List of Image URL's


         Recently, I needed to be able to load images from URLs into a WPF window without locking up the UI thread. After looking at multiple websites that posted how to do this or something similar, I wanted to share the solution I came up with after doing research on this topic.

What this does is takes a list of URLs and loads them asynchronously into the StackPanel without locking up the UI. If an image load fails, it inserts an error image and message.  For each image URL, a background worker is created to download the image using WebClient on a different thread. After each image is loaded the program will add it to the form. 

Here is the using statements. I had to give System.Windows.Shapes an alias because of the System.IO.Path namespace. They both contain an object called Path. This solved the ambiguous issue naming issue. Just checking to make sure the folder exists. If not, create it. This main try/catch is where it all happens. A rule of thumb, always leave breakpoints in your catches. Here we create a hard coded list of strings and loop over them and fetch each one in background worker. This will asynchronously load the images without locking up the UI thread. Here is the DoWork event. Its job is to download the image to the image folder and return the path of the downloaded image to the WorkCompleted event. If there is an issue we return NULL so we can load in our error image. In the work completed event we check for NULL and then add our controls to the StackPanel. I add a label then the image to the StackPanel's Children property. I load the images into a BitmapImage object by passing in the image path. Then I set it to the Image object which can be added to the StackPanel. This method is really handy and I found it in one of the source links. This will load up the error image we have in the solution. This is my first WPF project so I had to figure out how to do resource handling in WPF vs. Winforms/Webapps. There is not a huge difference, but it is a little different. Here is the XAML I added to the window. Note the use of the ScrollViewer around the StackPanel node.


Download Example

Sources:
http://stackoverflow.com/questions/8266475/how-to-download-image-synchronously-in-background
http://stackoverflow.com/questions/569561/dynamic-loading-of-images-in-wpf
http://stackoverflow.com/questions/6250240/how-to-add-a-scrollbar-to-a-stackpanel



Unknown

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard.

0 comments: