Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specified Visual is already a child of another Visual or the root of a CompositionTarget

Tags:

wpf

xaml

f#

prism

WPF Visualizer Visual Tree canvas

canvas.Children.Add poly |> ignore

Specified Visual is

  1. already a child of another Visual or
  2. the root of a CompositionTarget.

Don't think it's 1), not sure what 2) is?

Using Visual Studio 2010, F# 2.0, WPF, ... not XAML

like image 869
Art Scott Avatar asked Jun 03 '10 23:06

Art Scott


1 Answers

It's a bit hard to diagnose the problem without a relevant code sample, but maybe the problem is that you tried to add the same polygon to the canvas' children twice.

This is the code I burped up to reproduce your error:

type SimpleWindow() as this =
    inherit Window()

    do
        let makepoly size corners =
            let size = 192.0
            let angle = 2.0 * Math.PI / float corners
            let getcoords size angle = new Point(size * cos angle, size * sin angle)

            let poly = new Polygon(Fill = Brushes.Red)
            poly.Points <- new PointCollection([for i in 0..corners-1 -> getcoords size (float i * angle)])
            poly

        let canvas = new Canvas(HorizontalAlignment = HorizontalAlignment.Center,
                                VerticalAlignment = VerticalAlignment.Center)

        let poly = makepoly 192.0 5
        Canvas.SetLeft(poly, canvas.Width / 2.0)
        Canvas.SetTop(poly, canvas.Width / 2.0)

        canvas.Children.Add poly |> ignore //this works
        this.AddChild canvas |> ignore

SimpleWindow().Show()

If I add another canvas.Children.Add poly it crashes with your error message.

canvas.Children.Add poly |> ignore 
canvas.Children.Add poly |> ignore //this fails, poly already exists on the canvas

In order to fix the error, I first called canvas.Children.Remove to remove the specific child that was present in order to replace it by another.

canvas.Children.Add poly |> ignore 
canvas.Children.Remove poly
canvas.Children.Add poly |> ignore //this works, because the previous version is gone

I hope this fixes your problem.

like image 156
cfern Avatar answered Feb 22 '23 05:02

cfern