New Here?
My name is Nir and I'm the founder of Nbd-Tech, this blog is about things that interest me, so you can find posts on productivity, running a software company and obscure technological topics.
If you like what you read you can
subscribe to the blog feed or
follow me on twitter.
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