SyntaxHighlighter

Monday, March 29, 2010

WPF: Dynamically create a Table

Being new to WPF, there are a few funnies you'd need to know about before being able to create a simple table with text.

First, one can't simply add a Table within a Grid container. Tables need to be housed within a FlowDocument. One also need a container to display these FlowDocuments. I found the FlowDocumentScrollViewer to be the simplest. Some code to display a blank table:
<FlowDocumentScrollViewer
VerticalScrollBarVisibility="Disabled"
HorizontalScrollBarVisibility="Disabled">
<FlowDocument>
<Table Name="myTable"></Table>
</FlowDocument>
</FlowDocumentScrollViewer>

To populate the table programmatically with some basic text one need to follow the next procedure (the code is pretty much self-explanatory):
int cols = 5;
int rows = 10;

for (int c = 0; c < cols; c++)
myTable.Columns.Add(New TableColumn());

for (int r = 0; r < rows; r++)
{
TableRow tr = new TableRow();

for (int c = 0; c < cols; c++)
tr.Cells.Add(New TableCell(New Paragraph(New Run("Some Text"))));

TableRowGroup trg = new TableRowGroup();
trg.Rows.Add(tr);
myTable.RowGroups.Add(trg);
}

I must say that this approach (a Run within a Paragraph within a TableCell within a Row within a RowGroup) isn't terribly intuitive and the process seems a bit tedious when only trying to create a simple table.