Wojtek P Wojtek P - 22 days ago 10
C# Question

WPF Flow Document: adjust cells height when added in code behind

I have a FlowDocument with a Table inside. When I create the table directly in XAML and when some cell content is divided into two lines, all cells are automatically fit and the entire row is of equal height.

<TableRow Name="TestRow">
<TableCell BorderThickness="1,0,1,1" BorderBrush="LightGray">
<Paragraph>1</Paragraph>
</TableCell>
<TableCell BorderThickness="0,0,1,1" BorderBrush="LightGray">
<Paragraph>This is sentence which is divided into two lines</Paragraph></TableCell>
<TableCell BorderThickness="0,0,1,1" BorderBrush="LightGray">
<Paragraph>123</Paragraph></TableCell>
<TableCell></TableCell>
</TableRow>


enter image description here

But when I want to create the table dynamically in code behind, the cells have different heights.

tableProducts.RowGroups[0].Rows.Add(new TableRow());
TableRow currentRow = tableProducts.RowGroups[0].Rows[1];
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("1")) { BorderThickness = new Thickness(1, 0, 0, 1), BorderBrush = Brushes.LightGray }));
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("This is sentence which is divided into two lines")) { BorderThickness = new Thickness(1, 0, 1, 1), BorderBrush = Brushes.LightGray }));
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("123")) { BorderThickness = new Thickness(1, 0, 0, 1), BorderBrush = Brushes.LightGray }));


enter image description here

I can't find any solution on how to align the cells heights when they are created in code behind. Is there any way to solve this problem?

Answer

Change new TableCell(new Paragraph(...) { BorderThickness = ... }) to new TableCell(new Paragraph(...)) { BorderThickness = ... }

So the reason is Paragraph takes not all space from TableCell, and its border is inside of cell. But if you try to paint TableCell's border, everything will work fine.