Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataGrid Column Width Auto and Scrollbar

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.

like image 904
Brent Avatar asked Nov 29 '12 17:11

Brent


2 Answers

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="*" />
like image 140
Alexander Bell Avatar answered Oct 31 '22 21:10

Alexander Bell


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.

like image 40
Brent Avatar answered Oct 31 '22 20:10

Brent