我在 MVVM 中打印文档的命令为:
private void OKButton_Click(object sender, RoutedEventArgs e)
{
PrintDocument doc = new PrintDocument();
doc.PrintPage += new EventHandler<PrintPageEventArgs>(doc_PrintPage);
doc.Print("Payment Receipt");
this.DialogResult = true;
}
void doc_PrintPage(object sender, PrintPageEventArgs e)
{
Grid pGrid = new Grid();
pGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(30) });
pGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(665, GridUnitType.Star) });
pGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(30) });
pGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(30) });
pGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
pGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(20) });
// Stretch to the size of the printed page
pGrid.Width = e.PrintableArea.Width;
pGrid.Height = e.PrintableArea.Height;
// Assign the XAML element to be printed
Grid parentGrid = grdReceipt.Parent as Grid;
parentGrid.Children.Remove(grdReceipt);
pGrid.Children.Add(grdReceipt);
Grid.SetColumn(grdReceipt, 1);
Grid.SetRow(grdReceipt, 1);
// Stretch to the size of the printed page
pGrid.Width = e.PrintableArea.Width;
//grdReceipt.Height = e.PrintableArea.Height;
// Assign the XAML element to be printed
e.PageVisual = pGrid;
// Specify whether to call again for another page
e.HasMorePages = false;
}
当它执行 doc.Print() 它给我错误,因为对话框必须是用户启动的。请帮忙...