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