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://applicati开发者_Python百科on:,,,/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.
This code is working fine
Uri uri = new Uri("/Assets/default.png", UriKind.Relative);
BitmapImage imgSource = new BitmapImage(uri);
profileImage.Source = imgSource;
or
BitmapImage image = new BitmapImage(new Uri("/Assets/default.png", UriKind.Relative));
profileImage.Source = image;
There is no problem in your first code. At the end of that code you should add the StackPanel to your window or the grid inside the window. Also notice that the image's Build Action must be "Resource" and in your image URI ("/MyProject;component/Images/image1.png"), "MyProject" should be the name of your assembly and not the name of your project. Check your assembly name in the Application tab of the project properties.
精彩评论