Print a DataGrid in WPF

In WPF, a Visual is an object that is parent class of all user interfaces including UIElement, Containers, Controls, UserControls, and even Viewport3DVisual. The PrintVisual prints a Visual object. That means, by using the PrintVisual method, we can print any control, container, Window or user control.

The following code snippet in creates a PrintDialog object and calls its PrintVisual method by passing a UserControl to print the UserControl. Using this method, we can print any controls in WPF including a Window, page, or a ListBox.   

PrintDialog printDlg = new PrintDialog();

UserControl1 uc = new UserControl1();

printDlg.PrintVisual(uc, "User Control Printing.");

 


What if you want to print a Grid control or any other control?

Very simple. Just pass the Grid or other control in the PrintVisual method of PrintDialog.

PrintDialog printDlg = new PrintDialog();

printDlg.PrintVisual(grid1, "Grid Printing.");

How about printing the entire Window?

Again very simple. This time, you pass "this" that is the object of current Window where you are writing this code.



PrintDialog printDlg = new PrintDialog();

printDlg.PrintVisual(this, "Window Printing.");