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??
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With