如何在WPF中打印表格
本文关键字:打印 表格 WPF | 更新日期: 2023-09-27 17:57:38
I在WPF中编程。我用大量数据构建了一个表(DataGrid)(6列100行),我想知道如何打印它?
我对此做了很多搜索,但还没有找到解决方案。当我打印时,它只为我打印一页(大约30行的表),就这样。
以下是应该在DataGrid表上工作的代码:
System.Windows.Controls.PrintDialog Printdlg = new System.Windows.Controls.PrintDialog();
if ((bool)Printdlg.ShowDialog().GetValueOrDefault())
{
System.Windows.Size pageSize = new System.Windows.Size(Printdlg.PrintableAreaWidth, Printdlg.PrintableAreaHeight);
// sizing of the element.
MyDataGrid.Measure(pageSize);
MyDataGrid.Arrange(new Rect(5, 5, pageSize.Width, pageSize.Height));
Printdlg.PrintVisual(MyDataGrid, Title);
}
有人能给我写一个如何正确打印DataGrid表的简单代码吗?非常感谢。
对于WPF中的打印数据网格,您必须获取并使用给定的代码。
Xaml
<StackPanel>
<DataGrid AutoGenerateColumns="False" Margin="12,0,0,0" Name="dataGrid1" HorizontalAlignment="Left" VerticalAlignment="Top" ItemsSource="{Binding}" AlternatingRowBackground="LightGoldenrodYellow" AlternationCount="1">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Image" Width="SizeToCells" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Path=Image}" Width="100" Height="50" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Make" Binding="{Binding Path=Make}"/>
<DataGridTextColumn Header="Model" Binding="{Binding Path=Model}"/>
<DataGridTextColumn Header="Price" Binding="{Binding Path=Price}"/>
<DataGridTextColumn Header="Color" Binding="{Binding Path=Color}"/>
</DataGrid.Columns>
</DataGrid>
<Button Content="Print" Click="OnDataGridPrinting" Width="80" Height="30" />
</StackPanel>
代码
private void OnDataGridPrinting(object sender, RoutedEventArgs e)
{
System.Windows.Controls.PrintDialog Printdlg = new System.Windows.Controls.PrintDialog();
if ((bool)Printdlg.ShowDialog().GetValueOrDefault())
{
Size pageSize = new Size(Printdlg.PrintableAreaWidth, Printdlg.PrintableAreaHeight);
// sizing of the element.
dataGrid1.Measure(pageSize);
dataGrid1.Arrange(new Rect(5, 5, pageSize.Width, pageSize.Height));
Printdlg.PrintVisual(dataGrid1, Title);
}
}
这是经过测试的代码。