Styling a WPF layout grid background (of each cell, row, column)

Mladen Mihajlovic picture Mladen Mihajlovic · Feb 19, 2009 · Viewed 90k times · Source

I would like to know if there is any way to style a WPF layout grid's cells, rows and columns. I've been trying to find any information and the few mentions I've found have not been that informative.

I would like to style the grid to look like the one in the linked screenshot.

If the actual control does not support it, can I inherit it somehow and do it then? I am quite new to WPF so any help would be very appreciated.

One other thing, I know I can style each and every control within the grid, but it seems like overkill. I would like to have a grid that does it itself.

screenshot http://img21.imageshack.us/img21/2842/capturehz8.png

Answer

Vegar picture Vegar · Feb 19, 2009

@Dan recommends WPF Unleashed, which I'm currently reading. Just this morning, I come across a section addressing your question.

Chapter 6, Page 161:

FAQ: How can I give Grid cells background colors, padding, and borders like I can with cells of a HTML Table?

There is no intrinsic mechanism to give Grid cells such properties, but you can simulate them pretty easily thanks to the fact that multiple elements can appear in any Grid cell. To give a cell a background color, you can simply plop in a Rectangle with the appropriate Fill, which stretches to fill the cell by default. To give a cell padding, you can use auto sizing and set the Margin on the appropriate child element. For borders, you can again use a Rectangle but give it an explicit Stroke of the appropriate color, or you can simply use a Border element instead.

Just be sure to add such Rectangles or Borders to the Grid before any of the other children (or explicitly mark them with the ZIndex attached property), so their Z order puts them behind the main content.

Btw, WPF Unleashed rocks. Its very well written, and the print in full color makes it even more easier to read.