Setting max autogenerate width on autogenerated columns in a datagrid

痴心易碎 提交于 2019-12-11 08:37:54

问题


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?


回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/7272071/setting-max-autogenerate-width-on-autogenerated-columns-in-a-datagrid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!