How can I achieve a dashed or dotted border in WPF?

dan picture dan · Jun 1, 2011 · Viewed 63.6k times · Source

I have a ListViewItem that I am applying a Style to and I would like to put a dotted grey line as the bottom Border.

How can I do this in WPF? I can only see solid color brushes.

Answer

Rand Scullard picture Rand Scullard · Jul 2, 2013

This worked great in our application, allowing us to use a real Border and not mess around with Rectangles:

<Border BorderThickness="1,0,1,1">
   <Border.BorderBrush>
      <DrawingBrush Viewport="0,0,8,8" ViewportUnits="Absolute" TileMode="Tile">
         <DrawingBrush.Drawing>
            <DrawingGroup>
               <GeometryDrawing Brush="Black">
                  <GeometryDrawing.Geometry>
                     <GeometryGroup>
                        <RectangleGeometry Rect="0,0,50,50" />
                        <RectangleGeometry Rect="50,50,50,50" />
                     </GeometryGroup>
                  </GeometryDrawing.Geometry>
               </GeometryDrawing>
            </DrawingGroup>
         </DrawingBrush.Drawing>
      </DrawingBrush>
   </Border.BorderBrush>

   <TextBlock Text="Content Goes Here!" Margin="5"/>
</Border>

Note that the Viewport determines the size of the dashes in the lines. In this case, it generates eight-pixel dashes. Viewport="0,0,4,4" would give you four-pixel dashes.