无法通过嵌套类型访问外部类型的非静态成员

Cannot access a nonstatic member of outer type via nested type

此代码将在打印预览中添加保存工具提示,并将图片框保存为 PDF 格式。

 class SavePrint : System.Windows.Forms.PrintPreviewDialog
        {
            public SavePrint()
                : base()
            {
                if (this.Controls.ContainsKey("toolstrip1"))
                {

                    ToolStrip tStrip1 = (ToolStrip)this.Controls["toolstrip1"];
                    ToolStripButton button1 = new ToolStripButton();
                    button1.Text = "Save";

                    button1.Click += new EventHandler(SaveDocument);
                    button1.Visible = true;
                    tStrip1.Items.Add(button1);


                }
            }

            public void SaveDocument(object sender, EventArgs e)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Title = "Save As PDF";
                sfd.Filter = "PDF|*.pdf";
                sfd.InitialDirectory = @"Desktop";

                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    Bitmap bmp = new Bitmap(pictureBox.Image);//GETTING THE ERROR HERE
                    Graphics gr = Graphics.FromImage(bmp);

                    PdfDocument doc = new PdfDocument();
                    doc.Pages.Add(new PdfPage());
                    XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);

                    xgr.DrawImage(bmp, 0, 0);
                    doc.Save(sfd.FileName);
                    doc.Close();
                }
            }
        }

我在这一行收到错误 "Bitmap bmp = new Bitmap(pictureBox.Image)" 我应该怎么做才能继承我的 pictureBox?

将 class SavePrint 的构造函数更改为具有以下签名:

    class SavePrint : System.Windows.Forms.PrintPreviewDialog
    {
        readonly Form1 parent;
        public SavePrint(Form1 parent)
            : base()
        {
            this.parent = parent;

            // Remainder as before
        }
    }

然后当您构造 SavePrint 时,将适当的实例 Form1 传递给构造函数。

            SavePrint savePrint = new SavePrint(this);

完成后,您的 SavePrint 将能够访问其字段和属性:

            Bitmap bmp = new Bitmap(parent.pictureBox.Image);

顺便说一下,您应该包装所有 disposables in using 语句,如下所示:

            using (Bitmap bmp = new Bitmap(parent.pictureBox.Image))
            using (Graphics gr = Graphics.FromImage(bmp))
            {
            }