views:

431

answers:

2

I'm a beginner just beginning to work with Silverlight with a very basic question. I want to display a .png image. I have already done it in the page.xaml file but I would like to do it in code (C#) so that I can add and remove images while my program is running. I have seen some code in which you add an image to the Children of a Canvas, but when I do this no images are ever displayed. Could someone provide some code and where to put it? Here is what I've been working with. There are no exceptions, but no image appears.

page.myCanvas.Children.Add(LoadImage("Image/MrBlue"));


public Image LoadImage(string resource)
    {

        Image img = new Image();

        Uri uri = new Uri(resource, UriKind.Relative);

        ImageSource imgSrc = new System.Windows.Media.Imaging.BitmapImage(uri);

        img.SetValue(Image.SourceProperty, imgSrc);

        return img;

    }

The image is set to "Resource" and "Do not Copy."

+1  A: 

Debugging Silverlight can be a pain, although it's quite possible to set up in VS2008 (which you might already have done. If you haven't feel free to ask...) and that can catch some of the 'simple' errors like having the wrong Uri for the image you want. Your code looks fine to me, although what I'm using is slightly different. If you want an example from a working app, the function I use for loading images is:

public void ShowPicture(Uri location)
        {
            Image pic = new Image();
            pic.Source = new BitmapImage(location);
            Grid.SetColumn(pic, 1);
            Grid.SetRow(pic, 1);
            LayoutRoot.Children.Add(pic);
        }

Note that I have a using statement that includes System.Windows.Media.Imaging.

Even without full debugging, a utility like fiddler that shows the http requests might help track down bad Uris in code, which is all I can think of that might be wrong here. Hope it helps.

Raumornie
A: 

Hi there Stefan,

I tested your code and it works fine for me, so as Raumornie already hinted, it would seem to most likely be an issue with the path to the image. As per your code, is the image file located in a folder called Image in your Silverlight project and just named MrBlue? On a quick look, it seems to be missing the .png, or?

Good luck!

Ola Karlsson