【问题标题】:Grid child is already another visual or the root of a compositionTargetGrid child 已经是另一个视觉对象或 compositionTarget 的根
【发布时间】:2016-03-03 17:28:59
【问题描述】:

我想将所有图像从列表设置为网格。但是我在使用Children.Add 在网格中添加第二张图像时遇到问题。 这是我的例子:

 List<Image> images = new List<Image>(8);
 images.AddRange(Enumerable.Repeat(new Image(), 8));//8 empty 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;
}

然后在这样的一个函数调用中:

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++;
  }
}

我遇到运行时错误:Additional information: Specified Visual is already a child of another Visual or the root of a CompositionTarget.

我不明白为什么,因为我得到了 8 张不同的图像,而且我不知道如何解决这个问题。

【问题讨论】:

  • 有 XAML 来配合这个吗?您是否 100% 确定 LayoutRoot 是您期望的 Grid?
  • 看起来有问题的图像是在您将其添加到 LayoutRoot 之前作为子图像添加的。你检查过image.Parent 是否为空吗?
  • 我发现问题。我回答。
  • 我知道您已经找到了解决方案,但我添加了一个带有详细问题描述的答案。

标签: c# wpf children


【解决方案1】:

问题在于创建图像的代码。

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

这是一个图像对象,集合中有 8 个引用。

Enumerable.Repeat 的文档说:

元素
类型:TResult
要重复的

new Image() 的值是该图像的引用
这意味着您有 8 个对集合中同一对象的引用。

您可以通过比较列表中的第一个条目和第二个条目来轻松验证。

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

解决方案是使用for 循环来实例化图像。

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

【讨论】:

  • 这很有趣也很有逻辑。谢谢。
【解决方案2】:

似乎问题在于创建图像。 现在我不创建 8 个空图像,而是创建图像,然后添加到列表中。现在开始工作了:

for(int i = 0; i < 8; i++)
{
  Image a = new Image();
  BitmapImage b = new BitmapImage();
  b.BeginInit();
  b.UriSource = new Uri("path");
  b.EndInit();
  a.Source = b;
  a.Width = 50;
  a.Height = 50;
  images.Add(a);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 2015-08-31
    • 2012-03-07
    • 1970-01-01
    相关资源
    最近更新 更多