We can use the Line XAML element to draw lines in XAML and the Line class in WPF represents the XAML Line element. Learn here how to draw a Line in WPF. In this article, we will see how to use the LineSegment to draw a line.
Besides drawing lines using the Line element, we can also use the LineSegment element. The LineSegment is useful when a line becomes a part of a graphics path or a larger geometric object.
The LineSegment object represents a line between a start point and an end point. The LineSegment class has one property, Point that represents the end point of the line. The start point is a part of the path.
The following XAML code snippet creates a line segment. A Path object is used to draw an arc by setting a PathGeomerty as Path.Data.
  1. <Path Stroke="Black" StrokeThickness="1">
  2. <Path.Data>
  3. <PathGeometry>
  4. <PathGeometry.Figures>
  5. <PathFigureCollection>
  6. <PathFigure StartPoint="0,100">
  7. <PathFigure.Segments>
  8. <PathSegmentCollection>
  9. <LineSegment Point="200,100" />
  10. </PathSegmentCollection>
  11. </PathFigure.Segments>
  12. </PathFigure>
  13. </PathFigureCollection>
  14. </PathGeometry.Figures>
  15. </PathGeometry>
  16. </Path.Data>
  17. </Path>
The output looks like Figure 1.
LineSegment.jpg
Figure 1
The following code snippet dynamically creates the line segment shown in Figure 1.
  1. private void CreateLineSegment()
  2. {
  3. PathFigure pthFigure = new PathFigure();
  4. pthFigure.StartPoint = new Point(10, 100);
  5. LineSegment lineSeg = new LineSegment ();
  6. lineSeg.Point = new Point(200, 100);
  7. PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();
  8. myPathSegmentCollection.Add(lineSeg);
  9. pthFigure.Segments = myPathSegmentCollection;
  10. PathFigureCollection pthFigureCollection = new PathFigureCollection();
  11. pthFigureCollection.Add(pthFigure);
  12. PathGeometry pthGeometry = new PathGeometry();
  13. pthGeometry.Figures = pthFigureCollection;
  14. Path arcPath = new Path();
  15. arcPath.Stroke = new SolidColorBrush(Colors.Black);
  16. arcPath.StrokeThickness = 1;
  17. arcPath.Data = pthGeometry;
  18. arcPath.Fill = new SolidColorBrush(Colors.Yellow);
  19. LayoutRoot.Children.Add(arcPath);
  20. }