wpf。隐藏瓷砖刷溢出的简单方法

wpf. Easy way to hide tile brush overflow

我使用 DrawingBrush 来显示拖动标记 - 虚线。

<Rectangle Height="19" Width="7">
    <Rectangle.Fill>
        <DrawingBrush TileMode="Tile"
                      Viewbox="0,0,2,2"
                      Viewport="0,0,4,4"
                      ViewportUnits="Absolute"
                      ViewboxUnits="RelativeToBoundingBox">
            <DrawingBrush.Drawing>
                <DrawingGroup>
                    <GeometryDrawing Brush="#FF6D6D6D">
                        <GeometryDrawing.Geometry>
                            <EllipseGeometry Center="1,1"
                                             RadiusX="1"
                                             RadiusY="1" />
                        </GeometryDrawing.Geometry>
                    </GeometryDrawing>
                </DrawingGroup>
            </DrawingBrush.Drawing>
        </DrawingBrush>
    </Rectangle.Fill>
</Rectangle>

问题 - 无法与 Height=auto 一起使用,点图块可能被切片:

有没有简单的方法来隐藏不完整的图块?

您可以通过一个简单的自定义 FrameworkElement 实现所需的结果,它只绘制适合元素宽度和高度的完整圆圈:

public class DragMarker : FrameworkElement
{
    public static readonly DependencyProperty ForegroundProperty =
        Control.ForegroundProperty.AddOwner(typeof(DragMarker));

    public Brush Foreground
    {
        get { return (Brush)GetValue(ForegroundProperty); }
        set { SetValue(ForegroundProperty, value); }
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
        for (int y = 0; y < (int)ActualHeight / 4; y++)
        {
            for (int x = 0; x < (int)ActualWidth / 4; x++)
            {
                drawingContext.DrawEllipse(Foreground, null,
                    new Point(x * 4 + 2, y * 4 + 2), 1, 1);
            }
        }
    }
}