17

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.

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Brent
  • 1,378
  • 2
  • 16
  • 30

2 Answers2

28

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="*" />
Alexander Bell
  • 7,842
  • 3
  • 26
  • 42
  • 5
    This solution prevents the grid from getting a horizontal scrollbar in the event that it is not wide enough to fit the contents of all columns. – dlf Oct 19 '16 at 18:53
13

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.

mauris
  • 42,982
  • 15
  • 99
  • 131
Brent
  • 1,378
  • 2
  • 16
  • 30
  • You could also look to the TextRenderer.MeasureText property and set the minwidth equal to it. – Eduardo Brites Nov 30 '12 at 12:47
  • 1
    -1 won't compile with standard WPF and .NET 4.5; not much use to say it works with a **custom** **Datagrid** if the code is not supplied –  Apr 02 '14 at 02:21
  • 9
    -1 also **AsParallel()** is generally a big no no when dealing with GUI elements –  Apr 02 '14 at 02:45
  • hmm, well worked fine when I was using it, no longer at that company so don't have access to that code anymore. – Brent Apr 02 '14 at 13:02
  • @MickyDuncan I got a former colleague to double check and this code is still being used in production and compiles fine there for WPF .NET 4.5. As well as the AsParallel() is appropriate for speed when dealing with many columns which is what the situation was. – Brent Apr 04 '14 at 19:56
  • 2
    @Brent **AsParallel().ForEach()** will use the [thread pool](http://stackoverflow.com/questions/15122756/difference-between-threadpool-queueuserworkitem-and-parallel-foreach). Regarding DataGrid thread safety if I may quote MSDN: _"Any instance members are not guaranteed to be thread safe"_ http://msdn.microsoft.com/en-us/library/system.windows.controls.datagrid.aspx –  Apr 07 '14 at 23:30
  • 1
    @MickyDuncan you correct there, it may not be thread safe, however the action being preformed in this instance is fine as we know we are the only ones changing these settings at the time this code is exicuted. – Darren Apr 08 '14 at 13:47
  • 1
    It says that ForEach is not valid to use for datagrid. – Incisor Aug 20 '18 at 21:10