将图片从usercontrol传递到Form

时间:2018-01-02 21:53:52

标签: c# user-controls

我有一个带有1个面板的主表格, 该面板有10个用户控件和 每个用户控件都有图片框。

主要形式:

private void Form1_Load(object sender, EventArgs e)    
{

    Picturebox1.Image=....

    for(int i=0;i<10;i++)
    {
        uscontrol a=new uscontrol()
        {
            usimage=Image.Fromfile....  
        };
        panel1.Controls.Add(a);
    }
}

用户控制:

public Image usimage
    {
        get { return imagebox.Image; }
        set { imagebox.Image = value; }
    }

当我点击其中一个用户控件时,如何将该用户控件的图像传递给主窗体并在Picturebox1中显示, 谢谢。

1 个答案:

答案 0 :(得分:0)

首先,您需要将MouseClickEvent添加到每个uscontrol。要实现这一点,请将Form1_Load修改为此。

Picturebox1.Image=....
for(int i=0;i<10;i++)
{
    uscontrol a=new uscontrol()
    {
        usimage=Image.Fromfile....  
    };
    a.MouseClick += new MouseEventHandler(USControl_Clicked); //Note this added line 
    panel1.Controls.Add(a);
}

然后,您需要在USControl_Clicked代码中添加From1

private void USControl_Clicked(object sender, MouseEventArgs e)
{
    //Here we cast sender to your uscontrol class and access usimage
    Picturebox1.Image = (sender as uscontrol).usimage; 
}
相关问题