WPF DataGrid 列宽自动和滚动条
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13631694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF DataGrid Column Width Auto and Scrollbar
提问by Brent
I have a DataGrid with many columns.
我有一个包含许多列的 DataGrid。
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.
Width="Auto"
如果窗口比所有列窄,我想要滚动条显示所有内容。如果窗口更宽,我希望列跨越空白空间,因此没有死空间。
Basically I want the column minimum width to fully fit contents or header. And expand to larger if window wider.
基本上我希望列的最小宽度完全适合内容或标题。如果窗口更宽,则扩展到更大。
采纳答案by Brent
In XAML set DataGrid ColumnWidth="Auto"
在 XAML 中设置 DataGrid ColumnWidth="Auto"
In UserControl constructor add
在 UserControl 构造函数中添加
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.
将此与自定义 DataGrid 一起使用并且效果很好。
回答by Alexander Bell
In order to "fill" all horizontal space in WPF DataGrid
as you specified, make sure you have these properties set in XAML:
为了“填充”DataGrid
您指定的WPF 中的所有水平空间,请确保您在XAML 中设置了以下属性:
<DataGrid
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Stretch"
ColumnWidth="*" />