我想使用路径画一些线。运行该程序时,它总是向我显示错误。错误发生在以下句子:“ myPathSegmentCollection.Add(myLineSegment [i]);”
可以构建解决方案。调试时,它显示“元素已经是另一个元素的子元素”

以下是我的功能:

public void drawline(Point endP)
{
    PathFigenter code hereure myPathFigure = new PathFigure();
    myPathFigure.StartPoint = endP;

    LineSegment [] myLineSegment = new LineSegment[5];
    Point myPoint = new Point();
    LineSegment line = new LineSegment();
    PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();
    for (int i = 0; i < 5; i++)
    {
        myPoint.X = i + 10.0;
        myPoint.Y = i+1.0;
        line.Point = myPoint;
        myLineSegment[i] = line;
        myPathSegmentCollection.Add(myLineSegment[i]);
    }

    myPathFigure.Segments = myPathSegmentCollection;

    PathFigureCollection myPathFigureCollection = new PathFigureCollection();
    myPathFigureCollection.Add(myPathFigure);

    PathGeometry myPathGeometry = new PathGeometry();
    myPathGeometry.Figures = myPathFigureCollection;

    myPath.StrokeThickness = 1;
    myPath.Data = myPathGeometry;
}


有没有人可以帮忙?谢谢!

最佳答案

问题是您在循环中重新使用了LineSegment。这些只能作为单个控件的父项,因此尝试多次添加同一项会引发异常。

要修复它,请在循环中创建一个新的LineSegment

for (int i = 0; i < 5; i++)
{
    myLineSegment[i] = new LineSegment() {
       Point = new Point(i + 10.0, i + 1.0);
    };
    myPathSegmentCollection.Add(myLineSegment[i]);
}

09-13 04:31