Category / Section
How to set the content based column width when merge cell applied in WPF DataGrid (SfDataGrid)?
1 min read
WPF DataGrid (SfDataGrid) does not provide the direct support to set the content based column width when a cell is merged. You can set the content based column width when a cell is merged by customizing the column sizing operations by overriding GridColumnSizer and set it to SfDataGrid.GridColumnSizer.
this.dataGrid.GridColumnSizer = new GridColumnSizerExt();public class GridColumnSizerExt : GridColumnSizer
{
public GridColumnSizerExt()
{
}
protected override Size GetCellSize(Size rect, GridColumn column, object data, GridQueryBounds bounds)
{
//return empty size for merged cell
var rowIndex = this.DataGrid.ResolveToRowIndex(data);
var columnIndex = DataGrid.Columns.IndexOf(column);
var covererdCellInfo = this.DataGrid.CoveredCells.GetCoveredCellInfo(rowIndex, columnIndex);
if (covererdCellInfo != null)
return Size.Empty;
return base.GetCellSize(rect, column, data, bounds);
}
}
Refresh the autosize calculation after the merge cell operation performed in WPF DataGrid (SfDataGrid).
private void SfDataGrid_OnQueryCoveredRange(object sender, GridQueryCoveredRangeEventArgs e)
{
//merge the columns in a row by setting the column range using Left and Right properties of CoveredCellInfo.
if (e.RowColumnIndex.RowIndex == 3)
{
e.Range = new CoveredCellInfo(0, 2, 3, 3);
e.Handled = true;
}
//Refresh the autosize calculation after the merge cell operation performed in SfDataGrid
this.dataGrid.GridColumnSizer.ResetAutoCalculationforAllColumns();
this.dataGrid.GridColumnSizer.Refresh();
}

Take a moment to peruse the WPF DataGrid – AutoSize Columns, where you can find about autosize columns with code examples.
You can download the example from GitHub.