WPF Image Viewer Tutorial Part 2, The C# Code To Load Images

This is a part of the WPF image viewer tutorial: Introduction, Part 1.

This part of the tutorial has very little to do with Wpf, we just have to define and fill the data structure used to hold the image information.

First let's define a class to hold an image and it's file name, I've defined this class as a nested class of Window1 because it doesn't matter where we put it.

public class MyImage
{
   private ImageSource _image;
   private string _name;

   public MyImage(ImageSource image, string name)
   {
      _image = image;
      _name = name;
   }

   public override string ToString()
   {
      return _name;
   }

   public ImageSource Image
   {
      get { return _image; }
   }

   public string Name
   {
      get { return _name; }
   }
}

Now let's write a property that will scan the "My Pictures" folder and load all the images it finds.

public List<MyImage> AllImages
{
   get
   {
      List<MyImage> result = new List<MyImage>();
      foreach (string filename in
         System.IO.Directory.GetFiles(
         Environment.GetFolderPath(
         Environment.SpecialFolder.MyPictures)))
      {
         try
         {
           result.Add(
            new MyImage(
            new BitmapImage(
            new Uri(filename)),
            System.IO.Path.GetFileNameWithoutExtension(filename)));
         }
         catch { }
      }
      return result;
   }
}

BitmapImage is the WPF class that represents any type of bitmap, it inherits from ImageSource that represents any type of image.

The try..catch with an empty catch block is there to skip over any file that isn't an image (or an image that can't be loaded).

One last thing, just to make it easier for us later we'll add a line to Window1 contractor:

public Window1()
{
   InitializeComponent();
   DataContext = this;
}

This line will make the code in the next part more elegant.

That was all the C# we'll need for a while, in the next post we'll see the magic of data binding.

posted @ Thursday, August 16, 2007 4:03 PM

Comments on this entry:

# re: WPF Image Viewer Tutorial Part 2, The C# Code To Load Images

Left by David at 8/1/2008 6:48 PM

Code error
Page - The C# code to load images..

public List<myimage%gt; AllImages
{

Why did nobody point this out before ???

# re: WPF Image Viewer Tutorial Part 2, The C# Code To Load Images

Left by jam at 12/1/2008 7:59 AM

I can't get this compiling either. any advice?

Errors on:

public List AllImages

Error 1 Expected class, delegate, enum, interface, or struct

(and then a bunch more)

# re: WPF Image Viewer Tutorial Part 2, The C# Code To Load Images

Left by Nir Dobovizki at 12/2/2008 10:51 AM

jam, there are two things I can think of that cause that error message.

first option is that maybe you tried to compile the AllImages on it's own, it should be compiled as part of your window class.

second option is a copy-paste problem, I have a lot of those with code in HTML.

# re: WPF Image Viewer Tutorial Part 2, The C# Code To Load Images

Left by StCroixSkipper at 12/9/2008 9:15 PM

Works fine for me. Just like it is described.

# re: WPF Image Viewer Tutorial Part 2, The C# Code To Load Images

Left by StCroixSkipper at 12/9/2008 9:40 PM

Just a thought. It may not have been clear whether the AllImages property was part of the MyImage class or the Window1 class.

It is part of the Window1 class.

# re: WPF Image Viewer Tutorial Part 2, The C# Code To Load Images

Left by Maj3d at 3/18/2009 1:31 PM

Thanks , i ve been try all day to create an observable collection of Image to bind to a listview.
Any help?

# A good example of loading images in WPF, but a poor example of object oriented programming.

Left by Robert Goerss at 5/1/2009 6:04 PM

All told, this is a good example and rather straightforward.

Some of the code, however, sets a bad example for beginning developers.

For example, your AllImages property is misleading in its behavior in that it performs a function each time its accessor is called rather than doing the typical duties of a property; namely, returning a field that is either initialized in a constructor, set by a consumer or internal function, or is a lazily initialized singleton implementation.

The AllImages property should be refactored to a method, such as IEnumerable GetImageFileInfos(string directory) which would then be called with a given directory to search.

This new method could perform the exact same task that your AllImages property does for the sake of your example, but using this sort of method signature makes the method reusable and testable -- two key concepts of object oriented programming.

# re: WPF Image Viewer Tutorial Part 2, The C# Code To Load Images

Left by Tim at 7/31/2009 5:27 AM

had the same problem as the 'jam' user above, with error with that AllImages property.

The solution is to make sure you put the property in the CLASS definition, not in the namespace definition. Having a job where I'm in Java a lot, I'm not used to going two levels deep in braces before I get to my class object :)

# re: WPF Image Viewer Tutorial Part 2, The C# Code To Load Images

Left by Mohamed Ziyad at 3/18/2012 7:50 AM

Hi,Great tutorial. I want add some sound with each image. like show a cat, and pronounce the word. What is the easiest way to do it.
I have added a property to MyImage
private string _pronounciation;
assigned values to it too.
Trying to play the audio with
private void Button_Click(object sender, RoutedEventArgs e)
{

foreach (var item in AllImages)
{
wplayer.URL = item.Pronounciation;
wplayer.controls.play();
ImagePlaceHolder.Source = item.Image;
textBlockLable.Text = item.Name;

}
}
The problem is it only play pronunciation for single file. how to play one after the other ?

# re: WPF Image Viewer Tutorial Part 2, The C# Code To Load Images

Left by Nir at 3/19/2012 10:06 AM

Hi Mohamed Ziyad, to play the sounds one after the other you just have to play them one after the other.

the play method returns immidiatly, not after the sound finished playing so what you need to do is use the event that fires when the sound finishes and only then play the next file.

or maybe build a playlist if your media player control supports it.

Your comment:



 (will not be displayed)


 
 
 
Please add 7 and 2 and type the answer here: