If you create an application where the user can drag content on the screen you should consider enabling alignment features. Most graphics tools follow this approach. For example, in Visual Studio you get snaplines, which appear when the edge of the dragged control is aligned with other elements in the designer. Another common UI metaphor is drawing a pattern of lines on the screen. I liked to turn these on when user Expression Blend I find them helpful when positioning my graphic assets.
In this tip, I'll show you how to use the GeomrtryBrush to draw graph lines.
Example in Expression Blend
In Blend I click the 'Show snap grid' button on the bottom of the Artboard.
Expression Blend overlays a light gray grid of lines.
Creating the WPF GeometryBrush
The key to mimicking the Expression Blend snap grid is to create a GeometryBrush.
This example defines a brush in the root grid. In the DrawingGroup I create two lines perpendicular to each other. Then in the DrawingBrush I tell WPF to Tile (repeat) my brush repeatedly across the screen. The Viewport property is where I set the dimension of the tile.
Now I layer another Grid over the first and paint its Background with my DrawingBrush.
Here are the results.
By altering the viewport I can control the size of the tile. Here is what the Grid looks like when I set the Viewport="0,0,24,36".
Using the line brush on other shapes
Naturally I can use the brush on other WPF elements. Here is an example using an Ellipse.
This was first published in August 2010