指定的Visual已经是另一个Visual的子项或CompositionTarget的根

时间:2010-06-03 23:11:29

标签: wpf xaml f# prism

WPF Visualizer 视觉树 画布

canvas.Children.Add poly |>忽略

指定的视频

  1. 已经是另一个Visual或
  2. 的孩子
  3. CompositionTarget的根目录。
  4. 不要认为这是1),不确定2)是什么?

    使用Visual Studio 2010,F#2.0,WPF,...不是XAML

1 个答案:

答案 0 :(得分:12)

在没有相关代码示例的情况下诊断问题有点困难,但问题可能是您尝试将相同的多边形添加到画布'子项两次。

这是我为了重现你的错误而编写的代码:

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()

如果我添加了另一个canvas.Children.Add poly,则会因您的错误消息而崩溃。

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

为了解决这个错误,我首先调用了canvas.Children.Remove来移除存在的特定子节点,以便用另一个替换它。

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

我希望这可以解决您的问题。