1

I have a stack panel in my XAML page.

 <StackPanel Name="xamlimg" Orientation="Vertical" Grid.column="1">
 </StackPanel>

I want to add an image in this stackpanel using C# code behind the XAML page.

I have attempted using the structure below, but I can't seem to set the source right.

Image img = new Image();
img.Source= //Image Source here
xamlimg.Children.Add(img);

How do I set the image source and add it to the stackpanel?

Tester
  • 2,887
  • 10
  • 30
  • 60
  • don't create or manipulate UI elements in procedural code. That's what XAML is for. Learn MVVM. – Federico Berasategui Nov 13 '13 at 03:00
  • `Source` is a `Uri` not a `string`, I am not sure how you got that to compile. You will have to create the proper Uri to the imagefile – sa_ddam213 Nov 13 '13 at 03:00
  • It didn't compile, and I need to create it in the C# code because it does not need to be on the page for every instance, just once a condition is true. – Tester Nov 13 '13 at 03:23

2 Answers2

1

You can assign image source using below code:

image.Source = new BitmapImage(new Uri("/MyNameSpace;images/someimage.png", UriKind.Relative));

Thanks

Hitesh
  • 1,188
  • 5
  • 30
  • 52
  • I tried this. Got an exception error `The given System.Uri cannot be converted into a Windows.Foundation.Uri. ` – Tester Nov 13 '13 at 05:26
  • Plz look at this link :http://stackoverflow.com/questions/7569720/the-given-system-uri-cannot-be-converted-into-a-windows-foundation-uri and change uri as per above link. – Hitesh Nov 13 '13 at 05:30
  • Also look at this links: http://stackoverflow.com/questions/16200542/uri-formatting-on-image-source – Hitesh Nov 13 '13 at 05:34
0

it can be many causes, like your img source is inaccurate, the stackpanel is invisible, or it's (parent) size is collaped.

try hand code the img into the xaml, if it worked, then likely u need to look into the container/stackpanel, check it's property about visibility, size, etc.

if it doesn't work, look into the img tag, probably its the source.

Kelmen
  • 1,053
  • 1
  • 11
  • 24