Learning Silverlight Basics – Images

10 02 2010

I was asked a question regarding images in Silverlight from someone who wishes to learn more. To appease and educate; I’ll be sharing some basic info on how to work with Image objects in Silverlight.

Learning Silverlight Images Main

Inserting an Image object into your Silverlight project

There are two ways of doing most things in Silverlight; XAML and code. XAML often requires less work but code offers more precision in some cases. During this exercise, I’ll pretend that I’ve already added an image named “11.jpg” to my project in a folder named “Images”

Learning Silverlight Images 1To include this with XAML, I create a simple Image object like this: Learning Silverlight Images 2This will insert my image wherever I choose to put it. If I want to do the same thing in code, it’s a bit more complicated: 

Learning Silverlight Images 3

Here I create a BitmapImage object from the .jpg file. The Uri (uniform resource identifier) points to the file. In this case, I’m using a Uri that is Relative. This means that the location-string is relative to the project. This is similar to using the “~” sign in other languages. I then create an Image object which I call “img_eleven”. I take the source property of the Image and set it to my BitmapImage.

How about into a Stackpanel?

I’m glad you asked, headline. If I want this Image inside of a StackPanel I can do this both in XAML and in code. If I want to always add the Image, XAML is a better choice. If I want to add the Image as the result of a button click, code is a better choice.

To add the Image into a StackPanel using XAML, I write the following code:Learning Silverlight Images 4As I’m sure you’ve noticed by now, XAML often requires much less actual code and time. Now if I’m dead set to add the image with the help of code (as a part of an event maybe), this is what I’ll write:

Learning Silverlight Images 5

The only difference being that we’ve added a StackPanel element (which preferably already ought to have existed) and add out Image object to its collection of children.

That wasn’t so bad!

I agree! Let’s go to the movies.




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: