Search code examples
c#wpfchildren

Grid child is already another visual or the root of a compositionTarget


I want in set all images from list to grid. But I have problem with adding second image in grid with Children.Add. Here is my example:

 List<Image> images = new List<Image>(8);
 images.AddRange(Enumerable.Repeat(new Image(), 8));//8 empty images

Then setting images:

foreach (var image in images)
{
  BitmapImage b = new BitmapImage();
  b.BeginInit();
  b.UriSource = new Uri("path");
  b.EndInit();
  image.Source = b;
  image.Width = 50;
  image.Height = 50;
}

Then in one function call like this:

private void put_images()
{
  int i = 0;
  foreach (var image in images)
  {
    Grid.SetRow(image, i);
    Grid.SetColumn(image, i);
    LayoutRoot.Children.Add(image);//here is error
    i++;
  }
}

I got runtime error: Additional information: Specified Visual is already a child of another Visual or the root of a CompositionTarget.

I don't understand why, because I got 8 different images, and I don't know how to fix that problem.


Solution

  • The problem is the code where you create the images.

    images.AddRange(Enumerable.Repeat(new Image(), 8));
    

    This is one image object, with 8 references in the collection.

    The documentation of Enumerable.Repeat says:

    element
    Type: TResult
    The value to be repeated.

    The value of new Image() is the reference to that Image.
    Which means you have 8 references to the same object in the collection.

    You can easily verify that by comparing the first with the second entry in the list.

    images[0] == images[1] //=true
    

    A solution would be to use a for loop to instantiate the images.

    for(int i = 0; i < 8; i++) images.Add(new Image());