17
votes

I have a DataGrid with many columns.

I want Width="Auto" with scrollbar showing everything if window narrower than all columns. If window wider I want columns to span empty space so there is no dead space.

Basically I want the column minimum width to fully fit contents or header. And expand to larger if window wider.

2
can you post what xaml you have so far?d.moncada
If the width is set to auto, the scrollbar never appears.Eduardo Brites
@EduardoBrites modified question to add more clarificationBrent
OK. Did you see this answer? stackoverflow.com/a/4011435/1132646Eduardo Brites
@EduardoBrites actually just found that question, spent over hour on this and couldn't find anything before. I'll remove this question if that solves itBrent

2 Answers

27
votes

In order to "fill" all horizontal space in WPF DataGrid as you specified, make sure you have these properties set in XAML:

<DataGrid 
   HorizontalAlignment="Stretch" 
   HorizontalContentAlignment="Stretch" 
   ColumnWidth="*" />
9
votes

In XAML set DataGrid ColumnWidth="Auto"

In UserControl constructor add

dataGrid.Loaded += (s, e) => { // Column widths
    dataGrid.Columns.AsParallel().ForEach(column => {
        column.MinWidth = column.ActualWidth;
        column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
    });
};

Using this with a custom DataGrid and works great.