在C#中将事件从一个表单传播到另一个表单

如何单击一个表单中的按钮并以另一种forms更新TextBox中的文本?

如果您尝试使用WinForms,则可以在“子”表单中实现自定义事件。 单击“子”表单中的按钮时,可能会触发该事件。

然后,您的“父”表单将侦听事件并处理它自己的TextBox更新。

public class ChildForm : Form { public delegate SomeEventHandler(object sender, EventArgs e); public event SomeEventHandler SomeEvent; // Your code here } public class ParentForm : Form { ChildForm child = new ChildForm(); child.SomeEvent += new EventHandler(this.HandleSomeEvent); public void HandleSomeEvent(object sender, EventArgs e) { this.someTextBox.Text = "Whatever Text You Want..."; } } 

大致; 一个表单必须引用一些持有文本的底层对象; 此对象应触发更新文本的事件; 另一种forms的TextBox应该有一个订阅该事件的委托,它将发现底层文本已经改变; 一旦通知TextBox委托,TextBox应该查询底层对象以获取文本的新值,并使用新文本更新TextBox。

假设WinForms;

如果文本框绑定到对象的属性,则应在对象上实现INotifyPropertyChanged接口,并通知要更改的字符串的值。

 public class MyClass : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string title; public string Title { get { return title; } set { if(value != title) { this.title = value; if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs("Title")); } } } 

如上所述,如果绑定到Title属性 – 更新将“自动”到绑定到对象的所有表单/文本框。 我建议上面发送特定事件,因为这是通知绑定对象属性更新的常用方法。