this.datagrid.GridColumnSizer = new CustomerGridColumnSizer();
this.datagrid.QueryRowHeight += datagrid_QueryRowHeight;
private void datagrid_QueryRowHeight(object sender, QueryRowHeightEventArgs e)
{
if (e.RowIndex > this.datagrid.GetHeaderIndex())
{
e.Height = (this.datagrid.GridColumnSizer as CustomerGridColumnSizer).GetAutoRowWidth(e.RowIndex);
e.Handled = true;
}
}
public class CustomerGridColumnSizer : GridColumnSizer
{
public double GetAutoRowWidth(int rowIndex)
{
var rowData = this.DataGrid.GetRecordAtRowIndex(rowIndex);
double autoWidth = double.NaN;
foreach(var col in this.DataGrid.Columns)
{
var width = GetAutoWidth(col,rowData);
if (double.IsNaN(autoWidth))
autoWidth = width;
else if (width > autoWidth)
autoWidth = width;
}
return autoWidth;
}
public double GetAutoWidth(GridColumn column, object record)
{
var colIndex = this.DataGrid.Columns.IndexOf(column);
int scrollColumnIndex = this.DataGrid.ResolveToScrollColumnIndex(colIndex);
double colWidth = this.DataGrid.GetVisualContainer().ColumnWidths[scrollColumnIndex];
double rowHeight = this.DataGrid.GetVisualContainer().RowHeights.DefaultLineSize;
double resultWidth = 0;
int stringLenth = 0;
object rowData = null;
var clientSize = new Size(colWidth, rowHeight);
if (record == null)
return 0;
if (column is GridTemplateColumn)
{
var textsize = this.GetCellSize(clientSize, column, record, GridQueryBounds.Width);
if (textsize.IsEmpty)
return 0;
resultWidth = textsize.Width;
}
else
{
var text = this.GetDisplayText(column, record);
if (text.Length >= stringLenth)
{
stringLenth = text.Length;
rowData = record;
}
}
if (!(column is GridTemplateColumn))
{
var textsize = this.GetCellSize(clientSize, column, record, GridQueryBounds.Width);
resultWidth = textsize.Width;
}
return Math.Round(resultWidth);
}
} |