Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a grid in WPF

Tags:

c#

.net

wpf

drawing

I'm trying to create a user control in WPF to represent a Go board, which is essentially just a grid of black lines with dots on some of the intersections.

At the moment I'm using a Grid control to handle placement of the stones, but one of the difficulties is that the stones are placed on the intersections of the gridlines rather than between them, so if I want to draw the lines, they need to go through the centres of the grid cells.

I'm still quite new to WPF so I'm not really sure how I should be approaching this; should I be manually painting the lines every time the control renders (if so, how?), or is there a better way?

like image 335
Will Vousden Avatar asked Feb 23 '10 12:02

Will Vousden


People also ask

How do I add a Grid in WPF?

First Method: By typing XAML Code RowDefinitions property and a ColumnDefinition Element for each column inside the Grid. ColumnDefinitions property. By default, GridLines are invisible. For showing the GridLines, set the ShowGridLines property of the Grid to True.

How do I create a dynamic Grid in WPF?

The Grid class in WPF represents a Grid control. The following code snippet creates a Grid control, sets its width, horizontal alignment, vertical alignment, show grid lines, and background color. Grid DynamicGrid = new Grid();

What is Grid panel WPF?

A Grid Panel provides a flexible area which consists of rows and columns. In a Grid, child elements can be arranged in tabular form. Elements can be added to any specific row and column by using Grid.Row and Grid.Column properties. By default, a Grid panel is created with one row and one column.


1 Answers

You could approach to this in multiple ways.

For example. One way is to use DrawingBrush to fill Panel's background. Here are some DrawingBrush examples:

alt text
(source: microsoft.com)

Most likely you don't have to use Grid. For random positioning Canvas suits better. If you don't like brushes, you can use Geometries or Shapes to draw lines or other figures. I'm not referring you to DrawingVisuals because they may be slightly harder in understanding from start.

Updated: found this article on CodeProject: Draw a Boardgame in WPF. Maybe you'll find it useful.

Hope this helps,

Cheers, Anvaka.

like image 73
Anvaka Avatar answered Oct 22 '22 07:10

Anvaka