Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[WPF]How to draw a grid on canvas?

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

Thanks for any useful links.

Grid

like image 575
ske Avatar asked Oct 29 '14 16:10

ske


1 Answers

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.

like image 177
King King Avatar answered Sep 29 '22 20:09

King King