How to refresh column width while adding records at run time in WPF DataGrid ?
SfDataGrid.ColumnSizer property (type of GridLengthUnitType) provides different in-built options to specify the column width based on the data present in the cell and available width. GridLengthUnitType.SizeToCells, GridLengthUnitType.Auto and GridLengthUnitType.AutoWithLastColumnFill options is used to set the width of the column with respect to the cell content.
The width of the columns are calculated while loading SfDataGrid and when you are adding the record at runtime, the width of the columns is not refreshed based on ColumnSizer. You can refresh ColumnSizer at runtime by calling SfDataGrid.GridColumnSizer.Refresh() method. When you are using GridLengthUnitType.SizeToCells, GridLengthUnitType.Auto or GridLengthUnitType.AutoWithLastColumnFill options, you can reset the previously calculated widths by calling SfDataGrid.GridColumnSizer.ResetAutoCalculationforAllColumns() method before calling Refresh method. You can reset the width for a particular column by using SfDataGrid.GridColumnSizer.ResetAutoCalculation() method. So that the width calculation is done only for the particular column that provides better performance.
In the following code example, ColumnSizer is refreshed at runtime after adding records.
C#
private void AddRecords_Click(object sender, RoutedEventArgs e) { var viewmodel = (this.DataContext as ViewModel); this.sfgrid.GridColumnSizer.ResetAutoCalculationforAllColumns(); viewmodel.Employees.Add(employee.GetEmployee(1)); viewmodel.Employees.Add(employee.GetEmployee(2)); this.sfgrid.GridColumnSizer.Refresh(); }
The following screenshot displays the column widths that are set based on its cell content.
Figure 1: Column Width Updated in grid
Sample Links