[Silverlight] An image loading control


Ok the title is not really explicit but in this post we’re going to see an image control which display the busy pointer that we saw in my previous post, until the image be loaded.

First we create the Xaml composed with two controls: an image and the Busy pointer.

<UserControl x:Class="xxx.ImageProgress"
    <Grid x:Name="LayoutRoot" Background="White">
        <Image x:Name="Image" Stretch="Fill" />
        <local:BusyPointer x:Name="Buffer" />

And some C#

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
namespace xxx
    public partial class ImageProgress : UserControl
        public ImageProgress()
        public BitmapImage Source
            get { return (BitmapImage)GetValue(SourceProperty); }
                SetValue(SourceProperty, value);
                value.DownloadProgress += new EventHandler<DownloadProgressEventArgs>(value_DownloadProgress);
                this.Image.Source = value;
        void value_DownloadProgress(object sender, DownloadProgressEventArgs e)
            if (e.Progress == 100)
        // Using a DependencyProperty as the backing store for Source.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(BitmapImage), typeof(ImageProgress), new PropertyMetadata(new PropertyChangedCallback(OnSourceChanged)));
        private static void OnSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
            ImageProgress source = sender as ImageProgress;
            if (source != null) source.Source = (BitmapImage)e.NewValue;
        private void BeginAnimation()
            this.Buffer.IsBusy = true;
        private void StopAnimation()
            this.Buffer.IsBusy = false;
            this.Buffer.Visibility = Visibility.Collapsed;

I created a Dependency Property for the image’s source. When this DP is changed, I download the image from the source we I display the busy pointer. When the download is complete I stop the animation and hide it.

This control can be really useful if your application uses images from external source like Flickr or Bing.

We could check the ImageFailed event for notifying the user if there is an error.

Live sample: http://broux.developpez.com/public/SL/ImageProgress/index.html (the image is 4MB).


Comments have been disabled for this content.