Line in WPF

The Line object represents a line shape and draws a line between two defined points. This article demonstrates how to create lines in WPF and XAML.

The Line object represents a line shape and draws a line between two defined points. The X1 and Y1 properties of the Line represent the start point and X2 and Y2 properties represent the end point of the line. The Stroke property sets the color of the line and StrokeThickness represents the width of the line. A line shape does not have an interior so Fill property has no affect on a line.
 
Creating a Line
 
The Line element in XAML creates a line shape. The following code snippet creates a Line by setting its start point (X1, Y1) to (50, 50) and end point (X2, Y2) to (200, 200). That means a line is drawn from point (50, 50) to (200, 200). The code also sets the color of the line to red and width 4.
  1. <Line  
  2.     X1="50" Y1="50"  
  3.     X2="200" Y2="200"  
  4.     Stroke="Red"  
  5.     StrokeThickness="4" />  
The output looks like Figure 4.
 
 
 
Figure 4. A line
 
The CreateALine method listed in Listing 6 draws same line in Figure 4 dynamically. LayoutRoot in the below code is ID of a Grid panel on the page. 
  1. /// <summary>  
  2. /// Creates a line at run-time  
  3. /// </summary>  
  4. public void CreateALine()  
  5. {  
  6.     // Create a Line  
  7.     Line redLine = new Line();  
  8.     redLine.X1 = 50;  
  9.     redLine.Y1 = 50;  
  10.     redLine.X2 = 200;  
  11.     redLine.Y2 = 200;  
  12.   
  13.     // Create a red Brush  
  14.     SolidColorBrush redBrush = new SolidColorBrush();  
  15.     redBrush.Color = Colors.Red;  
  16.   
  17.     // Set Line's width and color  
  18.     redLine.StrokeThickness = 4;  
  19.     redLine.Stroke = redBrush;  
  20.   
  21.     // Add line to the Grid.  
  22.     LayoutRoot.Children.Add(redLine);  
  23. }