C# WPF数据表格最后一列宽度="*"会折叠其他列

4
我正在使用一个数据网格,它会随着窗口大小水平拉伸。
因为我想要摆脱右侧生成的额外列,所以我将所有列的大小都设置为“自动”,除了最后一列。我将最后一列的大小设置为“*”。
最终,我成功地摆脱了右侧生成的额外列。
但是现在,当我填充数据网格时,除了最后一列之外的所有列的大小都会塌陷到它们的标题宽度。
为什么列的宽度是它们的标题宽度?我将它们的宽度设置为“自动”,它们应该也考虑到它们的单元格大小。
注意:我不想为列设置MinWidths,它们应该根据列和单元格大小自动调整大小。
谢谢。

1
发布相关的XAML。 - Federico Berasategui
1个回答

3

尝试使用以下代码:

private void FitToContent()
    {
        int numCols ;
        int i ;

        numCols = dg.Columns.Count() ;
        i = 0 ;

        // where dg is your data grid's name...
        foreach (DataGridColumn column in dg.Columns)
        {
            if(i < numCols - 1)
            { 
                //if you want to size ur column as per the cell content
                column.Width = new DataGridLength(1.0, DataGridLengthUnitType.SizeToCells);
                //if you want to size ur column as per the column header
                column.Width = new DataGridLength(1.0, DataGridLengthUnitType.SizeToHeader);
                //if you want to size ur column as per both header and cell content
                column.Width = new DataGridLength(1.0, DataGridLengthUnitType.Auto);
            }
            else
            {
                column.Width = new DataGridLength(1.0, DataGridLengthUnitType.Star);
            }
            i++ ;
        }
    }

请确保所有列的HorizontalScrollVisibility属性设置为Auto


是的,但我不想要额外自动生成的列。 - Trax
我将 "numCols = dg.Columns.Count()" 改为 "numCols = dg.Columns.Count()-1",在 if 语句中选择了 Auto 选项,并完全删除了 else 语句。完美地解决了问题!谢谢。 - Trax
我在Xaml文件中将最后一列的Width设置为“*”。 - Trax

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接