How to resize WPF DataGrid to fit its content?

前端 未结 5 1853
别那么骄傲
别那么骄傲 2020-12-28 14:47

The aim

I would like to set such size for the DataGrid (standard, from WPF) so all cells (text) would be fully visible. I have window with DockPanel, with DataGrid

5条回答
  •  滥情空心
    2020-12-28 15:22

    I just came out of the same problem where I had to give options in a data grid's column to fit its width as per the content of both header and cell. I used the following code:

    private void FitToContent()
        {
            // where dg is my data grid's name...
            foreach (DataGridColumn column in dg.Columns)
            {
                //if you want to size your column as per the cell content
                column.Width = new DataGridLength(1.0, DataGridLengthUnitType.SizeToCells);
                //if you want to size your column as per the column header
                column.Width = new DataGridLength(1.0, DataGridLengthUnitType.SizeToHeader);
                //if you want to size your column as per both header and cell content
                column.Width = new DataGridLength(1.0, DataGridLengthUnitType.Auto);
            }
        }
    

    Also I provided an option on columns to fit as per the display (datagrid's width). for that I used the same code above with the following minor change:

    column.Width = new DataGridLength(1.0, DataGridLengthUnitType.Star);

    FOR ALL COLUMNS : Make sure you keep HorizontalScrollVisibility to Auto.

提交回复
热议问题