0

I am trying to dynamically insert a WPF Image into a grid. I currently have some code that already does this, it iterates through a list of URLs and then takes the picture from that URL and creates an image and then inserts it into the grid at a specified location.

However, I coded this a few months ago and I have since forgotten how to do it properly. Looking back at my code, I have copied the relevant snippets into a new test method for debugging purpose. The "lite" version of the code clears all the Children and RowDefinitions of the grid, and then creates a new RowDefinition and an Image. It then inserts the image into the row.

RowDefinition def = new RowDefinition
{
    Height = new GridLength(400)
};

myGrid.RowDefinitions.Add(def);

Image img = new Image
{
    Source = new BitmapImage(new Uri(@"folderpath/myimage.png", UriKind.Relative)), 
    Margin = new Thickness(0, 5, 0, 5)
};

Grid.SetRow(img, 0);
Grid.SetColumn(img, 0);

myGrid.Children.Add(img);

But when this code is run it produces nothing. Nothing appears inside the grid.

It should be noted that inside my Visual Studio project I have a folder "folderpath" with a bunch of images that are copied upon building the project. If I add myimage.png to the project inside of VS, and run the code snippet above everything works. The image is created and placed inside the grid.

But if I do not add myimage.png to the VS project before building, and instead copy the file over to the correct directory using Windows Explorer and then run the code, it does not work. This makes me believe it may be a directory issue, but when testing Environment.CurrentDirectory it is as expected.

I am now at a loss, why does the image only appear when I've added it inside my VS project before building and not when I manually add it to the folder after the build has completed?

Thanks for your help

Lachlan Mather
  • 273
  • 1
  • 5
  • 16
  • Do you copy into `folderpath` below the Build Output folder, e.g. to `bin\Debug\folderpath`? And if you have a list of URLs, why don't you load the images directly from those? – Clemens Aug 31 '19 at 06:17

1 Answers1

-1

I have had a similar issue before with an image showing in the XML editor but not showing when the code is ran. It's actually the intended behavior.

This is because in the editor it will get the link even if it isn't included in the project. However, when you build your code it won't show anything that isn't included in the project. Best practice is to have an img or resource folder in your project where you put all your relevant resources in.

David
  • 134
  • 13