Gayatri
Gayatri

Reputation: 274

Print in PrintDocument Using MVVM Gives Error : Dialogs Must Be User Initiated

My Command For Print Document In MVVM As :

   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;
    }

When it Executes doc.Print() it gives me error as Dialogs Must Be user Initiated. Please Help...

Upvotes: 0

Views: 541

Answers (1)

flup
flup

Reputation: 27104

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

For security purposes, if a Silverlight application is a sandboxed application, file and print dialog boxes must be user-initiated. This means you must show them from a user-initiated action, such as the click event handler for a button. If you attempt to show a dialog box from non-user initiated code, a SecurityException will occur. In addition, there is a limit on the time allowed between when the user initiates the dialog and when the dialog is shown.

So is the OKButton_Click called when the user clicks on a button? And do you perhaps have a debug point somewhere in between the click and the execution of the actual printing?

Upvotes: 1

Related Questions