Question

I have a code in WPF C# that i use to load images from the web as such:

if (myImgURL != "")
{
    var imgBitmap = new BitmapImage();
    imgBitmap.BeginInit();
    imgBitmap.UriSource = new Uri(myImgURL, UriKind.RelativeOrAbsolute);
    imgBitmap.CacheOption = BitmapCacheOption.OnLoad;
    imgBitmap.EndInit();
    myImgControl.Source = imgBitmap;
}

It works perfectly but sometimes it takes a while before the images get displayed (if internet is slow and all). How can I have a ProgressRing (from the Mahapps.Metro toolkit) display and be enabled while the image loads and then disappear when the image is displayed?

I am not aware of any event trigger for when an image is being downloaded and when it is fully loaded.

Was it helpful?

Solution

Take a look at the following events in class BitmapSource (the base class of BitmapImage):


And just a note. You are creating a BitmapImage from an Uri and showing it immediately. Hence there is no need to set BitmapCacheOption.OnLoad (which afaik is necessary only if you load from a stream that should be closed immediately after EndInit). So you could shorten your code like this:

if (!string.IsNullOrEmpty(myImgURL))
{
    var imgBitmap = new BitmapImage(new Uri(myImgURL));
    myImgControl.Source = imgBitmap;

    if (imgBitmap.IsDownloading)
    {
        // start download animation here

        imgBitmap.DownloadCompleted += (o, e) =>
        {
            // stop download animation here
        };

        imgBitmap.DownloadFailed += (o, e) =>
        {
            // stop download animation here
        };
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top