0

我在 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() 它给我错误,因为对话框必须是用户启动的。请帮忙...

4

1 回答 1

1

http://msdn.microsoft.com/en-us/library/ff382752%28v=vs.95%29.aspx

出于安全考虑,如果 Silverlight 应用程序是沙盒应用程序,则文件和打印对话框必须由用户启动。这意味着您必须从用户启动的操作(例如按钮的单击事件处理程序)中显示它们。如果您尝试从非用户启动的代码中显示对话框,则会发生 SecurityException。此外,在用户启动对话和显示对话之间允许的时间有限制。

那么OKButton_Click当用户点击一个按钮时会被调用吗?您是否可能在单击和执行实际打印之间有一个调试点?

于 2013-03-13T09:43:40.473 回答