C# 从点列表中构建PathGeometry而无需创建大量其他类

C# 从点列表中构建PathGeometry而无需创建大量其他类,c#,pathgeometry,C#,Pathgeometry,我正在尝试从自定义点列表构建一个简单的多边形PathGeometry。我在上找到了下面的代码,它似乎工作得很好,只需对循环和添加线段进行简单的修改,但要完成看似相对简单的任务,似乎有大量不雅观的混乱。有更好的办法吗 PathFigure myPathFigure = new PathFigure(); myPathFigure.StartPoint = new Point(10, 50); LineSegment myLineSegment = new LineSegment(); myLin

我正在尝试从自定义点列表构建一个简单的多边形PathGeometry。我在上找到了下面的代码,它似乎工作得很好,只需对循环和添加线段进行简单的修改,但要完成看似相对简单的任务,似乎有大量不雅观的混乱。有更好的办法吗

PathFigure myPathFigure = new PathFigure();
myPathFigure.StartPoint = new Point(10, 50);

LineSegment myLineSegment = new LineSegment();
myLineSegment.Point = new Point(200, 70);

PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();
myPathSegmentCollection.Add(myLineSegment);

myPathFigure.Segments = myPathSegmentCollection;

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

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

Path myPath = new Path();
myPath.Stroke = Brushes.Black;
myPath.StrokeThickness = 1;
myPath.Data = myPathGeometry;

您可以将其封装在函数中,还可以合并一些语句

Path makePath(params Point[] points)
{
    Path path = new Path()
    {
        Stroke = Brushes.Black,
        StrokeThickness = 1
    };
    if (points.Length == 0)
        return path;

    PathSegmentCollection pathSegments = new PathSegmentCollection();
    for (int i = 1; i < points.Length; i++)
        pathSegments.Add(new LineSegment(points[i], true));

    path.Data = new PathGeometry()
    {
        Figures = new PathFigureCollection()
        {
            new PathFigure()
            {
                StartPoint = points[0],
                Segments = pathSegments
            }
        }
    };
    return path;
}

我不相信有更好的方法,但您可以将其封装在函数中(例如
Path makePath(Point[]points)
)。谢谢,这非常有效!我稍微修改了它,将一段添加回起点,但这只在使用某些函数绘制时才重要,因为其他函数似乎并不关心。(当然,我没有想到要把它包装成一个函数。我显然需要更多的咖啡因>)
Path myPath = makePath(new Point(10, 50), new Point(200, 70));