昨天被骂惨了!
因为我写了一个C#父窗体控制子窗体的方法,我把modifiers属性改成了public。本来只是说一下有这么个属性,没想到引起了这顿喷哈哈,虚心接受,感谢朋友们的支持。
我错了!我重新写!
最终效果,就是点主窗体的按钮,更改子窗体picturebox的图片
新建项目,添加一个主窗体Form1和子窗体Form2,,,我们的任务是,在主窗体点击按钮控制子窗体的picturebox控件
Form2子窗体代码:
namespace FormConnections
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
//建立一个公共函数用来更改pictureBox1的图片
public void SetPic()
{
pictureBox1.ImageLocation = "c#.jpg";
}
private void pictureBox1_Click(object sender, EventArgs e)
{
//点击图片清空,为了调试用
pictureBox1.Image = null;
}
}
}
Form1调用这个函数就可以了:
namespace FormConnections
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//实例化两个子窗体
Form2 f2 = null;
private void Form1_Load(object sender, EventArgs e)
{
//打开子窗体
f2 = new Form2();
f2.Show();
}
private void button2_Click(object sender, EventArgs e)
{
//执行Form2的公共函数
f2.SetPic();
}
}
}
子窗体代码不变,父窗体代码:
namespace FormConnections
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Form2 f2 = new Form2();
private void Form1_Load(object sender, EventArgs e)
{
//打开子窗体
f2.Show();
}
private void button2_Click(object sender, EventArgs e)
{
//用委托去执行子窗体的内容
this.Invoke(new Action(() =>
{
f2.SetPic();
}));
}
}
}
父窗体代码:
namespace FormConnections
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//定义绑定FORM2更改图片操作的事件
public event EventHandler ChangeForm2Pic;
private void Form1_Load(object sender, EventArgs e)
{
Form2 f2 = new Form2();
//父窗体加载时,实例化Form2,并绑定事件
ChangeForm2Pic += f2.ChangePicEvent;
f2.Show();
}
private void button2_Click(object sender, EventArgs e)
{
//点击按钮,执行事件
ChangeForm2Pic(this, new Form2.PicPathArg() { PicPath = "C#.jpg" });
}
}
}
子窗体代码:
namespace FormConnections
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
//内部函数
void GoSetPic(string picpath)
{
pictureBox1.ImageLocation = picpath;
}
internal void ChangePicEvent(object sender, EventArgs e)
{
//执行事件时,得到传递来的参数
PicPathArg thepicpath = (PicPathArg)e;
//执行内部函数
this.GoSetPic(thepicpath.PicPath);
}
public class PicPathArg : EventArgs
{
//传递主窗体的数据信息
public string PicPath { get; set; }
}
private void pictureBox1_Click(object sender, EventArgs e)
{
//点击图片清空,为了调试用
pictureBox1.Image = null;
}
}
}