Wednesday, February 11, 2009

Silverlight Tip of the Day # 8 – How to Dynamically Load and Display Images

Loading images in Silverlight is fairly straight forward. The first step is to create what’s called a Uniform Resource Identifier (URI). The URI is essentially a string that points to a resource. The resource can be locally in the project or out on the Internet. Images that are loaded locally must be first added to your Visual Studio project.

Image image = new Image();
Uri uri = new Uri("images/myImage.png", UriKind.Relative);
ImageSource img = new System.Windows.Media.Imaging.BitmapImage(uri);
image.SetValue(Image.SourceProperty, img)

Now, to display the image you will need to add it to the Children of an element that you have declared in your XAML. For example, let’s say you have created a Canvas object in your Page.xaml under the parent Grid object. Using the x:Name tag, give it the name “Map”:

"MainGrid">
  "Map">
   

Now, back in your Page.xaml.cs file you can dynamically add the image you just created to the canvas object like this:

Map.Children.Add(image);

Btw, declaring an image in your XAML works the same way. Example:

"images/MyImage.png">

Thank you, 

0 comments:

Post a Comment