5

I am creating stackpanel inside the gridview cell dynamically and placing a image control inside stackpanel but on the window only blank space coming, not the image
here is what i am doing

StackPanel Stkpnl = new StackPanel();

Image BgImg = new Image();
BitmapImage Img = new BitmapImage(new Uri(
    "Images/cellbg.png", UriKind.Relative));
BgImg.Source = Img ;

Stkpnl.Children.Add(BgImg );
user1544004
  • 207
  • 4
  • 9
  • 1
    Have you tried debugging to see if the Img is loaded - have you added the stackpanel to the visual tree? – Charleh Aug 10 '12 at 17:09
  • 1
    Possible duplicate of [Setting WPF image source in code](http://stackoverflow.com/questions/350027/setting-wpf-image-source-in-code) – secretgenes Feb 18 '16 at 05:58

3 Answers3

2

You need to use a Pack URI. See https://stackoverflow.com/a/1651397/486660

If you have a question as to what your Pack URI should look like, then temporarily add an Image control to your WPF page then goto the Source property and click the "..." button and navigate to your image. The property's text box will have the Pack URI in it.

Community
  • 1
  • 1
Jim
  • 2,034
  • 1
  • 22
  • 43
0

Your code seems to be correct , have you check that image is existing on the folder or the relative path is correct, if you have added this image later to the image folder than you have to set "Build Action" of a image to "Resource". right click on the image in solution explorer than you can set this property.

you should also check this question

Setting WPF image source in code

Community
  • 1
  • 1
Buzz
  • 6,030
  • 4
  • 33
  • 47
0
StackPanel Stkpnl = new StackPanel();
Image BgImg = new Image();    
String packuri = "pack://application:,,,/yourassemblyname;component/cellbg.png";
BgImg.Source = new ImageSourceConverter().ConvertFromString(packuri) as ImageSource;

Stkpnl.Children.Add(BgImg );

PS: To find the assembly name in visual studio 2012 go to "Project" in menu bar -> "setup properties"->Application.

secretgenes
  • 1,291
  • 1
  • 19
  • 39