Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverlight Image Loading

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 Answers

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.

like image 189
Raumornie Avatar answered Nov 29 '25 21:11

Raumornie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!