从类控制PictureBox

时间:2013-05-21 10:00:30

标签: c# winforms

我在C#中有一个小项目(Windows Forms Application)。我有77 PictureBoxes(pictureBox1,pictureBox2,pictureBox3,...)的形式,我想通过在类中声明一个新的图片框来控制所有图片,但是从一个新类(Access.cs)控制它们。

因为如果我通过每个pictureBox并添加一个click方法并且复制+粘贴代码并且每次更改pictureBox编号都会太长。

我已将图片设为公开,并尝试使用以下代码:

Access.cs:

using System.Windows.Forms;

public class Access
{
    PictureBox picBox = new PictureBox();

    public void PictureClicked()
    {
        picBox.Image = Properties.Resources.apple;
    }
}

Form1.cs中:

private void pictureBox1_Click(object sender, EventArgs e)
{
    Access ac = new Access();
    ac.PictureClicked();
}

但代码不起作用!!

2 个答案:

答案 0 :(得分:3)

我真的不知道你想做什么,但你可以尝试将对象发送到你的Access类:

private void pictureBox1_Click(object sender, EventArgs e)
{
    Access ac = new Access();
    ac.PictureClicked(sender);
}


 public void PictureClicked(Object Sender)
{
           picBox = (PictureBox)Sender;
           picBox.Image = Properties.Resources.apple;
 }

答案 1 :(得分:1)

Access.Cs

 public void pictureBox1_Click(object sender, EventArgs e)
        {
            PictureBox pi = (PictureBox)sender;

            pi.Image = Properties.Resources.alert__2_;
        }

Form1.cs的

 private void pictureBox2_Click(object sender, EventArgs e)
        {
            Form1 c =new Form1();
            c.pictureBox1_Click(sender, e);


        }

这里pictureBox2_Click所有图片框的这个事件