1

我在问题中的 XAML 直接取自关于 SO的这个问题。只是 XAML 创建了一个平铺的 DrawingBrush 以在画布的背景上呈现矩形(在我的例子中为正方形)。我的问题是,这个 XAML 仅在我将画布的宽度和高度设置为“自动”以外的任何值时才有效。但是当我将 canvasMain 的 Width 和 Height 设置为 Auto 时,背景上不会绘制任何正方形。

如何将我的宽度和高度设置为“自动”并让 DrawingBrush 在我的画布上渲染正方形?

这是我的 XAML:

<Window.Resources>
  <DrawingBrush x:Key="GridTile" Stretch="None" TileMode="Tile"
    Viewport="0,0 20,20" ViewportUnits="Absolute">
    <!-- ^^^^^^^^^^^ set the size of the tile-->
    <DrawingBrush.Drawing>
      <GeometryDrawing>
        <GeometryDrawing.Geometry>
          <!-- draw a single X -->
          <GeometryGroup>
            <!-- top-left to top-right -->
            <LineGeometry StartPoint="0,0" EndPoint="20,0" />

            <!-- top-left to bottom-left -->
            <LineGeometry StartPoint="0,0" EndPoint="0,20" />

            <!-- bottom-left to bottom-right -->
            <LineGeometry StartPoint="0,20" EndPoint="20,20" />

            <!-- top-right to bottom-right -->
            <LineGeometry StartPoint="20,0" EndPoint="20,20" />

          </GeometryGroup>
        </GeometryDrawing.Geometry>
        <GeometryDrawing.Pen>
          <!-- set color and thickness of lines -->
          <Pen Thickness="1" Brush="Silver" />
        </GeometryDrawing.Pen>
      </GeometryDrawing>
    </DrawingBrush.Drawing>
  </DrawingBrush>
  <DrawingBrush x:Key="OffsetGrid" Stretch="None" AlignmentX="Left" AlignmentY="Top">
    <DrawingBrush.Transform>
      <!-- set the left and top offsets -->
      <TranslateTransform X="0" Y="0" />
    </DrawingBrush.Transform>
    <DrawingBrush.Drawing>
      <GeometryDrawing Brush="{StaticResource GridTile}" >
        <GeometryDrawing.Geometry>
          <!-- set the width and height filled with the tile from the origin -->
          <RectangleGeometry Rect="0,0 160,160" />
        </GeometryDrawing.Geometry>
      </GeometryDrawing>
    </DrawingBrush.Drawing>
  </DrawingBrush>
</Window.Resources>

<Canvas Name="canvasMain" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Top" Width="Auto" Height="Auto" Background="{StaticResource OffsetGrid}"></Canvas>
4

1 回答 1

2

尝试更改对齐方式:

<Canvas Name="canvasMain" HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch" Width="Auto" Height="Auto" Background="{StaticResource OffsetGrid}"></Canvas>
于 2013-08-20T21:49:22.307 回答