Click here to Skip to main content
15,889,909 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
XML
Trying to display an image on either a stack panel or Image so I added both o see which I get to work, I also want to change images when buton is clicked
In my XAML
<StackPanel Height="518" HorizontalAlignment="Left" Margin="1196,58,0,0" Name="stackPanel1" VerticalAlignment="Top" Width="417" />

<Image Height="202" HorizontalAlignment="Left" Margin="522,457,0,0" Name="imgPhoto" Stretch="Fill" VerticalAlignment="Top" Width="435" />

For button 1 (Image)
imgPhoto.Source = new BitmapImage(new Uri("c:\\Temp\test.jpg"));

for button 2 (stackanel)
Image imgPhoto = new Image();
imgPhoto.Source = new BitmapImage(new Uri("c:\\Temp\test.jpg"));
stackPanel1.Children.Add(imgPhoto);

None of these methods work.
Any help is greatly appreciated
Posted
Comments
[no name] 20-Aug-14 19:52pm    
Your paths are invalid you either need to add a \ or add @ in front of your string and get rid of the extra \.

FYI in the future, "not working" is not a helpful description of any kind of a problem.
picasso2 20-Aug-14 22:30pm    
The path is correct, somehow the “\” dropped when trying to format the post.
In any case,
The program compiles without errors.
If I add other controls (text, button) , just to test it
TextBlock printTextBlock = new TextBlock();
printTextBlock.Text = "Demo Text";
stackPanel1.Children.Add(printTextBlock);

Button btn = new Button();
btn.Content = "Dynamic Button";
stackPanel1.Children.Add(btn);

it works fine but trying to add an image to either the stackpanel or Image controls

Image imgPhoto = new Image();
imgPhoto.Source = new BitmapImage(new Uri("c:\\Temp\\test.jpg"));
stackPanel1.Children.Add(imgPhoto);

No image is displayed in either control. The image is a 300x300
And thus the reason asking for help

Thank you
~P
picasso2 21-Aug-14 0:17am    
I tried to use the same code as ChauhanAjay recommended below. but the property BeginInit()/EndInit() cannot be found.

Image imgPhoto = new Image();
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri("c:\\Temp\test.jpg");
bitmap.EndInit();
imgPhoto.Source = bitmap;
[no name] 21-Aug-14 7:10am    
Funny. Once I fixed your paths so that the code works, your exact code work for me.

1 solution

Please change your code in the following format.
Image imgPhoto = new Image();
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri("c:\\Temp\test.jpg");
bitmap.EndInit();
imgPhoto.Source = bitmap;


Hope the above solution helps.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900