Introduction
The solution contains a LinesGrid control WPF project, and a sample WPF application showing how to use it.
Background
This control appeared as I needed to draw certain amount of horizontal and vertical lines with equal intervals on top of another controls. I decided to post it online, as it might be useful
for some of you.
Using the code
Basically, the control is rather simple. It consists of two Grids, one on top of another. The first
Grid is used to draw the vertical (from top to bottom) lines, while the second - the horizontal lines. Each of the Grids' Background properties is set
to a VisualBrush containing a tile with a black pixel.
<Grid Name="LayoutRoot">
<Grid>
<Grid.Background>
<VisualBrush x:Name="verticalLines" Viewport="0,0,0.2,1"
TileMode="Tile" Viewbox="0,0,2,1">
<VisualBrush.Visual>
<Canvas>
<Line Stroke="Black" StrokeThickness="1" X1="1" />
</Canvas>
</VisualBrush.Visual>
</VisualBrush>
</Grid.Background>
</Grid>
<Grid>
<Grid.Background>
<VisualBrush x:Name="horizontalLines" Viewport="0,0,1,0.1"
TileMode="Tile" Viewbox="0,0,1,30">
<VisualBrush.Visual>
<Canvas>
<Line Stroke="Black" StrokeThickness="1" X1="1" />
</Canvas>
</VisualBrush.Visual>
</VisualBrush>
</Grid.Background>
</Grid>
</Grid>
The control has four dependency properties declared: Columns, Rows, LineThickness and LineBrush.
While with the first two you can set the quantity of lines to draw vertically and horizontally, the LineThickness property allows to set the thickness
of the lines, and LineBrush defines the brush used to draw them.
The RecreateLines method
is used to calculate the needed height and width of the VisualBrushes' Viewports. In this method we also calculate
the Viewboxes' Height and Width (depending on the lines thickness needed):
private void RecreateLines()
{
if (this.ActualWidth == 0 || this.ActualHeight == 0)
{
return;
}
double cellWidth = this.ActualWidth / (this.LineThickness * this.Columns);
this.verticalLines.Viewbox = new Rect(0, 0, cellWidth, 1);
double cellHeight = this.ActualHeight / (this.LineThickness * this.Rows);
this.horizontalLines.Viewbox = new Rect(0, 0, 1, cellHeight);
double qv = (1d - this.LineThickness / this.ActualWidth) / this.Columns;
this.verticalLines.Viewport = new Rect(0, 0, qv, 1);
double qh = (1d - this.LineThickness / this.ActualHeight) / this.Rows;
this.horizontalLines.Viewport = new Rect(0, 0, 1, qh);
}
The method is called on Rows or Cells value change.
Notes
There also might be some better ways to accomplish drawing a grid of lines in WPF, though for my primary purpose (debugging) the way described in this article was enough.
P. S.
This is my first article on codeproject, so any responses are highly appreciated and
welcome!
Thank you!
Updated
- The
HorizontalLines and VerticalLines properties renamed to more obvious Rows and Columns; - Updated the
RecreateLines method - now the bottommost and rightmost lines are also drawn.