引言
绘制简单的网格只需创建一个网格画笔,同时将编辑器的变换持续应用于它,并将该画笔用作编辑器的 Background
。
因为我们绘制的网格是由线条组成的,而不是填充的,所以编辑器的 Background
将具有一些透明度,这意味着我们会看到下面控件的背景颜色。为了解决这个问题,将编辑器包装在一个 Grid
中,并设置其 Background
,或者设置 Window
的 Background。
1、xaml代码
使用 ViewportTransform
依赖属性使网格随视图移动。
<Window x:Class="MyProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:nodify="https://miroiu.github.io/nodify"
mc:Ignorable="d">
<Window.Resources>
<GeometryDrawing x:Key="SmallGridGeometry"
Geometry="M0,0 L0,1 0.03,1 0.03,0.03 1,0.03 1,0 Z"
Brush="{StaticResource NodifyEditor.SelectionRectangleBackgroundBrush}" />
<GeometryDrawing x:Key="LargeGridGeometry"
Geometry="M0,0 L0,1 0.015,1 0.015,0.015 1,0.015 1,0 Z"
Brush="{StaticResource NodifyEditor.SelectionRectangleBackgroundBrush}" />
<DrawingBrush x:Key="SmallGridLinesDrawingBrush"
TileMode="Tile"
ViewportUnits="Absolute"
Viewport="0 0 20 20"
Transform="{Binding ViewportTransform, ElementName=Editor}"
Drawing="{StaticResource SmallGridGeometry}" />
<DrawingBrush x:Key="LargeGridLinesDrawingBrush"
TileMode="Tile"
ViewportUnits="Absolute"
Opacity="0.5"
Viewport="0 0 100 100"
Transform="{Binding ViewportTransform, ElementName=Editor}"
Drawing="{StaticResource LargeGridGeometry}" />
</Window.Resources>
<Grid Background="{StaticResource NodifyEditor.BackgroundBrush}">
<nodify:NodifyEditor x:Name="Editor" Background="{StaticResource SmallGridLinesDrawingBrush}" />
<Grid Background="{StaticResource LargeGridLinesDrawingBrush}"
Panel.ZIndex="-2" />
</Grid>
</Window>