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

被折叠的 条评论
为什么被折叠?



