Dynamically Loading Images in SilverLight 1.0 using C#

18. April 2008 18:40

Here is an easy way to dynamically load images from a directory into your SilverLight 1.0 application using C#. I'm going to assume you already know how to set up your application to use an aspx (with codebehind) page instead of a static HTML page. If not, this article may be useful.

The aspx page (I'll call it sampleXAML.aspx) contains your XAML declaration for the SilverLight 1.0 application. For this elucidation, we will only have one main canvas. In it, we will call your loadImages() method from the codebehind.

  <%= loadImages() %>

In your codebehind (sampleXAML.aspx.cs), we dynamically load images that will be displayed in the SilverLight app. First will create a string variable that will house our XAML declaration for an image.

string strImages = @"<Image x:Name=""image-{0}"" Source=""{1}"" Canvas.Left=""{2}"" Canvas.Right=""{3}"" />;

I've included Canvas.Left and Canvas.Right so images will be placed in a cascading fashion to ensure they were all loaded.

Keep in mind you will need the following namespaces:


Next step, read in your files from a directory using the loadImages() method...

protected string loadImages()
  StringBuilder strXML = new StringBuilder();

  int intCounter = 0;

  DirectoryInfo dirs = new DirectoryInfo(MapPath("~/images")); //Change path here for a specific folder you want to read in from

  foreach (FileInfo fi in dirs.GetFiles("*.jpg"))
    strXml.AppendFormat(strImages, intCounter, "images/" + fi.Name, intCounter*100, intCounter*100);
  return strXML.ToString();

The strXML is used to build your <Image> XAML tag and is populated in the foreach loop by four parameters. You can add or remove parameters as needed, but at mininum you'll need the Source.

Note that I've filtered for JPGs. First, SilverLight 1.0 can only read JPGs and PNGs. Secondly, Windows loves to create the thumbs.db to display the cool little folder with tiny images of the pictures. While you may not get an error, it will attempt to create another <Image> XAML tag that is empty for that thumbs.db file.

When you run your application, the XAML generated should read to something similar:

<Image x:Name="image-0" Source="images/img01.jpg" Canvas.Left="0" Canvas.Right="0" />
<Image x:Name="image-1" Source="images/img02.jpg" Canvas.Left="100" Canvas.Right="100" />
<Image x:Name="image-2" Source="images/img03.jpg" Canvas.Left="200" Canvas.Right="200" />
<Image x:Name="image-3" Source="images/img04.jpg" Canvas.Left="300" Canvas.Right="300" />

The end. Post any questions you may have.

Tags: , ,


blog comments powered by Disqus

My Random Thought

I think the OCW is a great thing to have available to those who are in school, just finished school or just want to educate themself


John On Twitter