[WPF]How to draw a grid on canvas?

ske picture ske · Oct 29, 2014 · Viewed 13k times · Source

How to draw the following chart as a background on custom canvas inherited from Canvas - system ui element?

Thanks for any useful links.

Grid

Answer

King King picture King King · Oct 29, 2014

You can just set Canvas.Background to some DrawingBrush. This brush can just need to render a Rectangle (by using some RectangleGeometry). Because of supporting for TileMode, we can repeat this rectangle along both horizontal and vertical axes and make the full grid for you:

<Canvas>
    <Canvas.Background>
       <DrawingBrush TileMode="Tile" Viewport="-10,-10,40,40" 
                                     ViewportUnits="Absolute">
          <DrawingBrush.Drawing>
             <GeometryDrawing>                 
                <GeometryDrawing.Geometry>
                   <RectangleGeometry Rect="0,0,50,50"/>
                </GeometryDrawing.Geometry>
                <GeometryDrawing.Pen>
                   <Pen Brush="Gray" Thickness="1"/>
                </GeometryDrawing.Pen>
             </GeometryDrawing>
          </DrawingBrush.Drawing>
       </DrawingBrush>
    </Canvas.Background>
 </Canvas>

Note that you can draw something outside the Canvas but its Background is always inside its region. So you need to set the Size for your Canvas correctly.