Print Datagrid records in WPF

前端 未结 3 487
我寻月下人不归
我寻月下人不归 2021-01-01 04:08

I need to print datagrid records only. I used one code like this, but this one printed datagrid scroll bar also. I need only records.

PrintDialog printDlg =          


        
相关标签:
3条回答
  • 2021-01-01 04:36

    Hey For Print DataGrid in WPF you have to take <StackPanel> and use given code.

    Xaml Code is

     <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>
    

    And .CS code is

       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);
            }
        }
    

    Hope it helps you

    This is tested code.

    0 讨论(0)
  • 2021-01-01 04:48

    If you want to print all records from datagrid in wpf.I have already answere here with better explanation. see it. Print all data in the DataGrid in WPF

    0 讨论(0)
  • 2021-01-01 04:57

    Place your DataGrid in the ViewBox, so that you can get how you want. :)

    0 讨论(0)
提交回复
热议问题