[WPF]如何在画布上绘制网格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26635635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:40:02  来源:igfitidea点击:

[WPF]How to draw a grid on canvas?

c#.netwpfwpf-controlswpf-4.0

提问by ske

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

如何在继承自 Canvas-system ui 元素的自定义画布上绘制以下图表作为背景?

Thanks for any useful links.

感谢您提供任何有用的链接。

Grid

网格

回答by King King

You can just set Canvas.Backgroundto 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.Background为 some DrawingBrush。这个画笔只需要渲染一个矩形(通过使用 some RectangleGeometry)。由于支持TileMode,我们可以沿水平和垂直轴重复此矩形并为您制作完整的网格:

<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.

请注意,您可以在画布之外绘制一些内容,但其背景始终位于其区域内。因此,您需要正确设置 Canvas 的 Size。