Search code examples
c#wpfwpfdatagrid

Setting max autogenerate width on autogenerated columns in a datagrid


I have a DataGrid that I'm binding to DataTable that got filled by a SQL query. I would like the columns of this grid to be auto-generated with a width of up to a certain number of pixels, but still be expandable by the user if they want it to be wider. Currently the ColumnWidth property on the datagrid is set to SizeToHeader (which doesn't seem to work as described anyway, since it's still sizing to cell content).

Is there any way to set a max generation width?

Setting MaxColumnWidth prevents the user from resizing the column larger than that width.

I've also tried hooking into AutoGeneratedColumns, but since the rows aren't loaded yet the ActualWidth properties just represent the MinWidth I've set. Is there an event that fires once the datagrid finishes loading its initial set of rows?


Solution

  • Iterate over the column collection and get the width for each column. If the width is greater than the threshold set it to your maximum width. You would want to do this after the control has initialized.

    This article may be helpful: http://support.microsoft.com/kb/812422

    Something like this may work:

    foreach(var c in grid.Columns)
    {
        var width = c.Width;
        if(width > threshold)
        {
            c.Width = threshold;
        }
    }