Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Image to StackPanel in programmatically

Tags:

c#

wpf

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??

like image 419
KMC Avatar asked Jul 27 '11 07:07

KMC


2 Answers

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

uses by default UriKind.Absolute and not UriKind.Relative

If you wish to user UriKind.Relative - URI should be in different format. Have a look at MSDN

like image 134
elevener Avatar answered Sep 26 '22 19:09

elevener


No repro.

I Copy/Pasted your code to a Button handler and added 1 line:

  root.Children.Add(Sp);

Tip: Set a breakpoint at the end of this code and use the "WPF Tree Visualizer" to see if everything is where you think it is. It's the little looking glass in the Locals and Autos Windows.

like image 20
Henk Holterman Avatar answered Sep 25 '22 19:09

Henk Holterman