在WPF中如何重复使用背景刷?

10

谢谢您。

这个问题与这里的一个古老、未回答的问题非常相似:如何在文本框背景上绘制类似笔记本线条的线条?然而,它并不完全一样。

我想创建一个记事本,有像纸张一样的背景,但我不熟悉如何在XAML中重复使用画刷。您该怎么做?

编辑

以下是作为TextBox的解决方案:

<TextBox TextBlock.LineHeight="20" 
         TextBlock.LineStackingStrategy="BlockLineHeight" 
         Padding="20,10,20,20" TextWrapping="Wrap">
  <TextBox.Background>
    <DrawingBrush TileMode="Tile" Stretch="None" Viewport="0,0,20,20" 
                  ViewportUnits="Absolute" Opacity=".07">
      <DrawingBrush.Drawing>
          <GeometryDrawing>
              <GeometryDrawing.Pen>
                  <Pen Brush="RoyalBlue" />
              </GeometryDrawing.Pen>
              <GeometryDrawing.Geometry>
                  <LineGeometry StartPoint="0,0" EndPoint="20,0"/>
              </GeometryDrawing.Geometry>
          </GeometryDrawing>
      </DrawingBrush.Drawing>
    </DrawingBrush>
  </TextBox.Background>
  Now is the time for all good men to come to the aid of their country.
  Now is the time for all good men to come to the aid of their country.
  Now is the time for all good men to come to the aid of their country.
  Now is the time for all good men to come to the aid of their country.
  Now is the time for all good men to come to the aid of their country.
</TextBox>

关于建议的编辑:我同意,请将你的具体解决方案提取到一个单独的答案中。(如果需要,可能还可以添加有关LineHeightLineStackingStrategy如何解决对齐问题的说明) - H.B.
3个回答

11
<DrawingBrush TileMode="Tile" Stretch="None"
              Viewport="0,0,20,20" ViewportUnits="Absolute">
    <DrawingBrush.Drawing>
        <GeometryDrawing>
            <GeometryDrawing.Pen>
                <Pen Brush="Gray"/>
            </GeometryDrawing.Pen>
            <GeometryDrawing.Geometry>
                <LineGeometry StartPoint="0,0"
                              EndPoint="20,0"/>
            </GeometryDrawing.Geometry>
        </GeometryDrawing>
    </DrawingBrush.Drawing>
</DrawingBrush>

你想要调整什么来影响线条的粗细?显然 <Pen Thickness=".5" /> 不正确。谢谢。 - Jerry Nixon
@JerryNixon:实际上应该是 Pen.Thickness,如果线条对你来说没有变细,可能存在一些别名问题。 - H.B.

2
有趣,我也在做同样的事情。这是你需要的内容。你可能需要调整TileMode来设置平铺方向和ViewPort,最后两个数字应该是你的图像的宽度/高度(我不得不这样做,因为我的图像被拉伸了或者根本没出来)。
<ImageBrush x:Key="WindowBackground" ImageSource="/Images/Background.png" TileMode="Tile" ViewportUnits="Absolute" Viewport="0,0,4,4" />

您还可以更改ImageBrushStretch属性,使其正确显示。 - Prince Owen

0
使用ImageBrush。
<ImageBrush ImageSource="image.png" TileMode="Tile"/>

这是我得到的,但它只显示一次图像,居中。 - Mike Fulton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接