Xiao_ga
Xiao_ga

Reputation: 165

Drawing lines in windows phone 7?

I would like to draw some lines using Path. It always show me error when running the program. The error occurs at this sentence:"myPathSegmentCollection.Add(myLineSegment[i]);" The solution can be built. While debugging, it shows "Element is already the child of another element"

the following is my function:

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

Is there anyone can help? THX!

Upvotes: 2

Views: 1069

Answers (1)

Ron Warholic
Ron Warholic

Reputation: 10074

The problem is that you're re-using your LineSegment in the loop. These can only be parented to a single control and so trying to add the same item multiple times throws an exception.

To fix it create a new LineSegment in the loop:

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

Upvotes: 1

Related Questions