How to print a DataGrid in WPF, not a DataGridView

寵の児 提交于 2019-12-12 01:23:48

问题


"InvokePaint" is displaying error, "this" of the InvokePaint method is supposed to be a class, but i don't know which class it should be, any help will be appreciated.

SqlDataAdapter da = new SqlDataAdapter("Select * from CallRegister", data.getCon());
                DataTable dt = new DataTable("Call Reciept");
                da.Fill(dt);
                DataGrid dg = new DataGrid();
                dg.ItemsSource = dt.DefaultView;
                System.Drawing.Size m = new System.Drawing.Size((int)dg.Width, (int)dg.Height);

                System.Windows.Forms.PaintEventArgs myPaintArgs = new System.Windows.Forms.PaintEventArgs(e.Graphics, new System.Drawing.Rectangle(new System.Drawing.Point(0, 0),m));
                this.InvokePaint(dg, myPaintArgs);

回答1:


This method can be called only from WindowsForms control as MSDN says:

Raises the Paint event for the specified control. Namespace:
System.Windows.Forms Assembly: System.Windows.Forms (in System.Windows.Forms.dll)

So this code should be called from hosted WinForms control inside WPF project:

this.InvokePaint((dg, myPaintArgs); 

Update. To print Datagrid:

XAML:

<DataGrid  ItemsSource="{Binding Path=Persons, Mode=TwoWay}" Name="dataGrid"/>
<Button Grid.Row="1" Click="Button_Click" Content="Print DataGrid"/>

Code behind:

private void Button_Click(object sender, RoutedEventArgs e)
{            
   var pd = new PrintDialog();
   var result = pd.ShowDialog();
   if (result.HasValue && result.Value)
      pd.PrintVisual(dataGrid, "My WPF printing a DataGrid");
}



回答2:


 PrintDialog printDialog = new PrintDialog();
 printDialog.PrintVisual(dataGrid, "Print Grid");


来源:https://stackoverflow.com/questions/34032853/how-to-print-a-datagrid-in-wpf-not-a-datagridview

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