Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF datagrids and dynamic column widths

We have a custom DataGrid control that dynamically generates columns determined by an XML structure.

When creating each of the columns, we're giving it a starred unit type because we want to ensure theres never any horizontal scrolling in the DataGrid.

            DataGridTextColumn column = new DataGridTextColumn();
            column.Width = new DataGridLength(entity.DisplaySize, DataGridLengthUnitType.Star);

However, we've noticed that when the DataGrid is rendered, it renders with the minimum size given to the columns, then once the DataGrid is fully rendered it resizes the columns to properly fit within the DataGrid. This is causing a flicker effect.

Does anyone have any possible solutions? Maybe how to render the DataGrid in the background, then show once the columns are done fidgeting? Or any other ideas?

like image 621
flamebaud Avatar asked Sep 14 '12 16:09

flamebaud


1 Answers

This is, unfortunately, normal behavior. It has to do with the way the control is rendered. In WPF, you have layers upon layers of controls, and the DataGrid has no way of knowing what kinds of controls until it has finished rendering.

So the first layout pass creates the controls, but then it must go through a second pass to measure how large those controls are. Once it knows how large the controls are, it can then begin to resize the columns.

A DataGrid is an excellent example of a scenario where the highly configurable and dynamic layout system of WPF doesn't work. To get the kind of performance you are used to, you'll need to go with a non-WPF grid, one which is able to better predict its own hierarchy and thus perform these kinds of measurements without the need to pre-render everything. Such controls exist for WPF, but you have to find them.

Here's one from xceed: http://xceed.com/Grid_WPF_Intro.html?gclid=CNKE8rOBtrICFQfonAodHQ8AEA

Here's one from Telerik: http://www.telerik.com/products/wpf/gridview.aspx

(Because of the need to balance flexibility with performance, and the large number of features expected in a modern datagrid, this control has long been held as the pinnacle of control development. Good datagrids are extremely hard to build. In Excel, Microsoft built an entire application around, essentially, a glorified datagrid. All this to say, you probably won't find what you're looking for for free.)

See this question: WPF DataGrid Vs Windows Forms DataGridView

like image 116
JDB Avatar answered Oct 24 '22 00:10

JDB