Add Image to StackPanel in programmatically

Viewed 32158

I am trying to programmatically generate a StackPanel and add an Image to the StackPanel. Somehow I get an empty StackPanel. I do not see anything wrong with my code, and it didn't throw any exception:

StackPanel Sp = new StackPanel();
Sp.Orientation = Orientation.Horizontal;

Image Img = new Image();
BitmapImage BitImg = new BitmapImage(new Uri(
    "/MyProject;component/Images/image1.png", UriKind.Relative));
Img.Source = BitImg;

Sp.Children.Add(Img);

[EDIT]

I tried another way to add the Image and it works. It intrigues me because they seems to me essentially the same thing:

The following code WORKS (show image):

Image Img = new Image();
Img.Source = new BitmapImage(new Uri(
             "pack://application:,,,/MyProject;component/Images/image1.png"));

The following code does NOT WORK (image missing):

Image Img = new Image();
BitmapImage ImgSource = new BitmapImage(new Uri(
    "pack://application:,,,/MyProject;component/Images/image1.png",
    UriKind.Relative));
Img.Source = BitImg;

Why are they different??

4 Answers
Related