[WPF]How to draw a grid on canvas?

孤街醉人 提交于 2019-12-21 05:49:15

问题


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

Thanks for any useful links.


回答1:


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.



来源:https://stackoverflow.com/questions/26635635/wpfhow-to-draw-a-grid-on-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!