DataGrid not printing when created dynamically

Feb 4, 2009 at 11:39 PM

If a DataGrid is created at runtime (this is a requirement for me),  A PrintVisual simply doen't print anything.  It turns out the the DesiredSize of the DataGrid is not refreshed when columns are added dynamically.  Please note that if the DataGrid is created in xaml and columns are added at runtime, the same exact code works!!!  Any help would be greatly appreciated.  Here is some sample code to reproduce the problem.


printDlg = new PrintDialog();
if (printDlg.ShowDialog().GetValueOrDefault()) {



  //commenting the following line and creating the grid in xaml makes the code work
grdForPrinting = new DataGrid();

  //set up dummy grid columns
  for (int i = 0; i < 5; i++) {
    DataGridTextColumn colDef = new DataGridTextColumn();
    colDef.Header = "Header " + i;
    colDef.Width = 100;
  //set up some dummy height
  grdForPrinting.Height = 100;

  //center the grid and print (calls to Measure and Arrange are required before printing)


new Size(Double.PositiveInfinity, Double.PositiveInfinity));
  Size sizeGrid = grdForPrinting.DesiredSize;  //DesiredSize has a zero width here!!!!
  Point pointGrid = new Point((printDlg.PrintableAreaWidth - sizeGrid.Width) / 2,
                                                    (printDlg.PrintableAreaHeight - sizeGrid.Height) / 2);
new Rect(pointGrid, sizeGrid));
"Printing not working");