dotNET
dotNET

Reputation: 35400

DataGrid Autogenerated columns: Increasing width

Is there a way to increase the width of auto-generated columns by a fixed amount? I'm trying to do the following but it doesn't work:

private void dgvMailingList_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
     e.Column.Width += 30; 
}

Even e.Column.Width = e.Column.Width + 30; doesn't work because the default UnitType of Width is Auto and therefore e.Column.Width returns 1.0 instead of the actual pixel width. UnitType itself is read-only, so can't play with that either. ActualWidth is also set to 0 in AutoGeneratingColumn event. What's the correct way of doing this?

Upvotes: 1

Views: 1485

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81253

Columns are not rendered yet on UI when AutoGeneratingColumns event is raised. Hence ActualWidth is 0.0.

Use Loaded event to loop over columns and increase width by constant factor you want.

private void dataGrid_Loaded(object sender, RoutedEventArgs e)
{
    foreach (var column in ((DataGrid)sender).Columns)
    {
        column.Width = new DataGridLength(column.ActualWidth + 30);
    }
}

Upvotes: 5

Related Questions