尝试在WPF C#中实现Polyline,但抛出'Specified Visual已经是一个孩子'错误

问题描述 投票:0回答:1

我正在尝试实现一个Polylinefollowing this:WPF Drawing on Canvas with Mouse Events /就像在原始查询中我成功实现了解决方案线条绘制但注意到线条的波动。下一个解决方案表明使用Polyline解决了问题。然而,它正在抛出可怕的“指定的视觉已经是一个孩子”的错误。这些是相关的代码片段:

        private void Canvas_MouseDown_1(object sender, MouseButtonEventArgs e)
    {
        if (e.ButtonState == MouseButtonState.Pressed)
            currentPoint = e.GetPosition(MainCanvas);
        StartingPoint = currentPoint;

        if (ActiveDrawingTool == DRAW_ROADS)
        {
            polygonPoints = new PointCollection();
            polyLine = new Polyline();
        }

//等...

 private void Canvas_MouseMove_1(object sender, System.Windows.Input.MouseEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed && ActiveDrawingTool != 0
            && ActiveDrawingTool != DRAW_PLACENAMES)
        {
            if (ActiveDrawingTool == DRAW_ROADS)
            {

                polyLine.Stroke = new SolidColorBrush(Colors.Black);
                polyLine.StrokeThickness = 8;
                Point currentPoint = e.GetPosition(MainCanvas);
                polygonPoints.Add(currentPoint);
                polyLine.Points = polygonPoints;
                MainCanvas.Children.Add(polyLine);

            }

将折线添加到MainCanvas时会引发错误。奇怪的是,如果我不使用折线,它不会抛出此错误。我试图使用折线实时绘制连续线。

c# wpf canvas polyline
1个回答
0
投票

正如克莱门斯在评论中回答的那样:

错误消息非常清楚。 polyLine已经是MainCanvas的孩子了。你不能两次添加它。如果您已添加一次,请不要再次调用Add(polyLine)。或者在再次添加之前将其删除。或者创建一个新的折线。

这解决了这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.