如何给非静态面板添加事件?

问题描述 投票:0回答:1

首先,我想指出,我是 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。)

c# winforms eventhandler
1个回答
0
投票

改变

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

部分修复它。

可能我已经摆脱了这个线程问题,但是我如何获取我单击的图像以删除或编辑它的信息?

© www.soinside.com 2019 - 2024. All rights reserved.