Changing the source of an Image

Sometimes the things you think should be simple can cause you problems in Silverlight. I had a simple Image control on my page and I wanted to change its source depending upon a user selection. So I started with the obvious, myImage.Source = "newImage.jpg" only to be faced with "Cannot implicitly convert type ‘string’ to ‘System.Windows.Media.ImageSource’. Ok fine I’ll create a Uri. myImage.Source = new Uri("newImage", UriKind.Relative) Same problem. Hmm, ok so I’ll go via a Bitmap Image; myImage.Source = new BitmapImage(new Uri("newImage.jpg", UriKind.Relative)) but now I got an error on the page (in the JavaScript error panel). Grr. Well this time it was where the image was that was causing the problem. I’d put the images in a folder on the hosting site that was a peer to ClientBin and used a relative path, so rather than "newImage.jpg" I was actually using "../Images/newImage.jpg". Turns out it doesn’t like that one little bit. Assuming this was a security thing I put the Images folder under the ClientBin folder and that did the trick.

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s