使用MVVM在PrintDocument中打印时出错:对话必须是用户启动的

时间:2013-03-13 09:38:01

标签: xaml mvvm silverlight-5.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()时,它给出了错误,因为Dialogs必须是用户启动的。 请帮忙......

1 个答案:

答案 0 :(得分:1)

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

  

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

当用户点击按钮时调用OKButton_Click也是如此? 你可能在点击和执行实际打印之间的某个地方有一个调试点吗?