printing DataGrid in WPF

本文介绍了一个使用 WPF 中 DataGrid 控件进行打印的例子。通过 XAML 和 C# 实现了带有测试数据的 DataGrid,并提供打印功能。文章展示了如何设置 DataGrid 的属性、填充数据以及实现打印逻辑。

Here is an example of printing DataGrid in WPF.

 

XAML code:

<Window x:Class="WpfDataGridPrinting.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:dg="clr-namespace:Microsoft.Windows.Controls;assembly=WpfToolkit"

    Title="Window1" Height="300" Width="300">

    <StackPanel>

        <dg:DataGrid  Width="200" Height="150" HorizontalContentAlignment="Center"

                      Name="dataGrid"

                      AutoGenerateColumns="True" />

        <Button Content="Print" Click="OnDataGridPrinting"  Width="80" Height="30" />

    </StackPanel>

</Window>

 

In the code behind:

 

namespace WpfDataGridPrinting

{

    public partial class Window1 : Window

    {

        public Window1()

        {

            InitializeComponent();

            //set testing data

            DataTable employeeTalbe = new DataTable();

            DataColumn colID = new DataColumn("ID");

            DataColumn colName = new DataColumn("Name");

            employeeTalbe.Columns.Add(colID);

            employeeTalbe.Columns.Add(colName);


            for (int i = 0; i < 4; i++)

            {

                DataRow newRow = employeeTalbe.NewRow();

                newRow["ID"] = "ID" + " " + (i + 1).ToString();

                newRow["Name"] = "Name" + " " + (i + 1).ToString();

                employeeTalbe.Rows.Add(newRow);

            }

            dataGrid.ItemsSource = employeeTalbe.DefaultView;

        }

        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.

                dataGrid.Measure(pageSize);

                dataGrid.Arrange(new Rect(5, 5, pageSize.Width, pageSize.Height));

                Printdlg.PrintVisual(dataGrid, Title);

            }

        }

    }

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值