WPF DataGrid Column Width Auto and Scrollbar

早过忘川 提交于 2019-12-20 17:47:32

问题


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.


回答1:


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="*" />



回答2:


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.



来源:https://stackoverflow.com/questions/13631694/wpf-datagrid-column-width-auto-and-scrollbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!