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.
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”
To include this with XAML, I create a simple Image object like this: This 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:
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:As 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:
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.