通过确定列中最宽单元格的所需宽度是可能的。最宽的单元格可以通过循环遍历所有行来确定单元格的所需宽度并记住最大值来确定。
在本例中,所有列都进行了优化。值19可能是由左右单元格填充加上单元格边框粗细造成的。
void autoresizeColumns(Table table)
{
TableColumnCollection columns = table.Columns;
TableRowCollection rows = table.RowGroups[0].Rows;
TableCellCollection cells;
TableRow row;
TableCell cell;
int columnCount = columns.Count;
int rowCount = rows.Count;
int cellCount = 0;
double[] columnWidths = new double[columnCount];
double columnWidth;
// loop through all rows
for (int r = 0; r < rowCount; r++)
{
row = rows[r];
cells = row.Cells;
cellCount = cells.Count;
// loop through all cells in the row
for (int c = 0; c < columnCount && c < cellCount; c++)
{
cell = cells[c];
columnWidth = getDesiredWidth(new TextRange(cell.ContentStart, cell.ContentEnd)) + 19;
if (columnWidth > columnWidths[c])
{
columnWidths[c] = columnWidth;
}
}
}
// set the columns width to the widest cell
for (int c = 0; c < columnCount; c++)
{
columns[c].Width = new GridLength(columnWidths[c]);
}
}
double getDesiredWidth(TextRange textRange)
{
return new FormattedText(
textRange.Text,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface(
textRange.GetPropertyValue(TextElement.FontFamilyProperty) as FontFamily,
(FontStyle)textRange.GetPropertyValue(TextElement.FontStyleProperty),
(FontWeight)textRange.GetPropertyValue(TextElement.FontWeightProperty),
FontStretches.Normal),
(double)textRange.GetPropertyValue(TextElement.FontSizeProperty),
Brushes.Black,
null,
TextFormattingMode.Display).Width;
}