开发者

Setting max autogenerate width on autogenerated columns in a datagrid

开发者 https://www.devze.com 2023-04-01 02:21 出处:网络
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 b

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 describ开发者_高级运维ed 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?


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;
    }
}


From the documentation the Width property set on an individual DataGridColumn takes precedence over the ColumnWidth property. You might be able to iterate over the DataGridColumns in the AutoGeneratedColumns event and set individual Widths and have them stick.


I needed to modify rtalbot's code slightly to get this to work for my WPF/.net 4.5 project ... actualwidth and datagridlength:

        // fix extra wide columns
        foreach (var c in dgMain.Columns)
        {
            var width = c.ActualWidth;
            if (width > 200)
            {
                c.Width = new DataGridLength(200);
            }
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号