簡體   English   中英

c#在循環中動態創建一個EventHandler

[英]c# Dynamically creating an EventHandler in a loop

我正在嘗試在表單上動態創建一組圖像。 圖像渲染正常,但我不知道如何創建 eventHandlers。

    pictureBox.Click += new System.EventHandler(this.pictureBox);

這條線引起了問題。

 private void frmBorderlessMain_Load(object sender, EventArgs e)
   {
       int top = 10;
       int left = 10;
       int width = 200;
       int height = 150;
       var uutNames = MyObject.GetNames().ToArray();
       var uutImages = MyObject.GetImages().ToArray();
       for (int i = 0; i < uutNames.Length; i++)
       {
           System.Windows.Forms.PictureBox pictureBox = new System.Windows.Forms.PictureBox();


           Image newImage = Image.FromFile(uutImages[i]+".png");
           pictureBox.Image = ((System.Drawing.Image)(newImage));
           pictureBox.Location = new System.Drawing.Point(left, top);
           pictureBox.Name = "pictureBox"+i;
           pictureBox.Size = new System.Drawing.Size(200, 150);
           pictureBox.SizeMode =   
                     System.Windows.Forms.PictureBoxSizeMode.Zoom;
           pictureBox.TabIndex = i;
           pictureBox.TabStop = false;

           pictureBox.Click += new System.EventHandler(this.pictureBox);
           this.tabPage1.Controls.Add(pictureBox);
           left += width + 10;
           if ( (i > 0 ) && (i % 3) == 0)
           {
                    top += height + 10;
                    left = 10;
           }
       }
   }

附加信息:單擊圖像后,我希望打開一個新表單,顯示有關被單擊實體的詳細信息。 它將是相同的表單,但將根據單擊的圖像加載數據。

pictureBox.Click += new System.EventHandler(this.pictureBox);

這不是事件處理程序的使用方式。

拉姆達:

pictureBox.Click += (sender, eventArgs) => Console.WriteLine("HELP I WAS CLICKED OMG");

或者用一個函數:

pictureBox.Click += PictureBox_Click;

....

private void PictureBox_Click(object sender, EventArgs e)
{
    Console.WriteLine("Stop clicking me >:(");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM