通过接口实现,实现松耦合。
主窗体
public partial class mainform : Form { public mainform() { InitializeComponent(); } private void butMessage_Click(object sender, EventArgs e) { childform1 c1 = new childform1(); c1.Show(); childform2 c2 = new childform2(); c1.messageonList.Add(c2); c2.Show(); childform3 c3 = new childform3(); c1.messageonList.Add(c3); c3.Show(); } }
子窗体1
public partial class childform1 : Form { public childform1() { InitializeComponent(); messageonList = new List<ImessageOn>(); } //这个集合放我们的观察者 public List<ImessageOn> messageonList { get; set; } private void butMessage_Click(object sender, EventArgs e) { foreach(var messageon in messageonList) { messageon.ReceiveMessage("小明"); } } }
子窗体2、3
public partial class childform2 : Form,ImessageOn { public childform2() { InitializeComponent(); } public void ReceiveMessage(string str) { this.textMessage.Text = str + " " + DateTime.Now.ToString(); } }