首先,我想指出,我是 C# 的初学者。
我的代码是:
private static void addImageToPanel(imageData[] images, Panel panel)
{
Panel imagePanel;
PictureBox imageImage;
Label imageLabel;
Size imageSize = new()
{
Width = 80,
Height = 80,
};
Size imagePanelSize = new()
{
Width = 100,
Height = 100,
};
const int posX = 60;
const int posY = 140;
foreach (imageData image in images)
{
if (!panel.Controls.ContainsKey(image.key))
{
imagePanel = new()
{
Name = image.key,
Size = imagePanelSize,
Left = posX * x + margin,
Top = posY * y + margin,
Cursor = Cursors.Hand,
};
//Error here VVV toolStripClick (CS0120: An object reference is required for the non-static field, method, or property 'member')
imagePanel.Click += new EventHandler(toolStripClick);
imageLabel = new()
{
Name = image.key + "_text",
Text = image.name,
ForeColor = Color.White,
Font = new Font("Segoe UI", 8),
Dock = DockStyle.Bottom,
TextAlign = ContentAlignment.MiddleCenter,
};
imageImage = new()
{
Name = image.key + "_image",
Image = Image.FromFile("C:\\..."),
SizeMode = PictureBoxSizeMode.Zoom,
Size = fileSize,
Dock = DockStyle.Top,
};
panel.Controls.Add(imagePanel);
imagePanel.Controls.Add(imageLabel);
imagePanel.Controls.Add(imageImage);
}
}
}
其中“toolStripClick”是:
private void toolStripClick(object sender, EventArgs e)
{
contextMenuStrip1.Show(Cursor.Position.X, Cursor.Position.Y);
}
我不明白为什么这不起作用。将静态添加到“toolStripClick”没有帮助。
甚至尝试在添加所有图像后执行 for 循环,如下所示:
for (int i = 0; i < mainPanel.Controls.Count; i++)
{
mainPanel.Controls[i].Click += new EventHandler(toolStripClick);
}
除了警告(CS8622:可为空参考...)之外,它不显示任何错误,但它仍然不起作用。
编辑: 没关系,我刚刚发现从“addImageToPanel”中删除静态可以修复它,部分原因是它在面板上不起作用,但在标签上起作用......
有没有办法让它在面板上工作?或者有什么解决办法吗?
编辑2: 将“focusPanel”替换为“imagePanel”。 (我在复制粘贴时犯的错误。过去和现在都是 imagePanel 而不是 focusPanel。)
改变
private static void addImageToPanel(imageData[] images, Panel panel)
到
private void addImageToPanel(imageData[] images, Panel panel)
和
imagePanel.Click += new EventHandler(toolStripClick);
到
imageImage.Click += new EventHandler(toolStripClick);
imageLabel.Click += new EventHandler(toolStripClick);
部分修复它。
可能我已经摆脱了这个线程问题,但是我如何获取我单击的图像以删除或编辑它的信息?