1
votes

The XAML that I have in my question was taken directly from this question on SO. It's simply XAML that creates a tiled DrawingBrush to render rectangles (squares in my case) against the background of a canvas. My problem is that this XAML only works when I set the Width and Height of the Canvas to anything other than "Auto". But when I set the Width and Height of canvasMain to Auto then no squares are drawn on the background.

How can I have my Width and Height set to "Auto" and also have the DrawingBrush render the squares on my canvas?

Here is my 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>
1

1 Answers

2
votes

Try changing the alignments:

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