我正在尝试实现一个Polyline
following 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时会引发错误。奇怪的是,如果我不使用折线,它不会抛出此错误。我试图使用折线实时绘制连续线。
正如克莱门斯在评论中回答的那样:
错误消息非常清楚。
polyLine
已经是MainCanvas
的孩子了。你不能两次添加它。如果您已添加一次,请不要再次调用Add(polyLine)
。或者在再次添加之前将其删除。或者创建一个新的折线。
这解决了这个问题。