在C#中将事件从一个窗体传递到另一个窗体

6
如何在一个窗体中点击按钮并更新另一个窗体中的文本框?
3个回答

15

如果您正在尝试使用WinForms,您可以在"子"窗体中实现自定义事件。当您的"子"窗体中的按钮被点击时,您可以触发该事件。

"父"窗体将监听该事件并处理自己的文本框更新。

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...";
    }
}

1
大致上来说,一个表单必须引用某个持有文本的基础对象;该对象应在文本更新时触发事件;另一个表单中的 TextBox 应该有一个订阅该事件的委托,它将发现基础文本已更改;一旦通知了 TextBox 委托,TextBox 就应查询新文本值的基础对象,并使用新文本更新 TextBox。

0

假设使用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属性,则更新将“自动”传递到绑定到该对象的所有表单/文本框。我建议使用此方法而不是发送特定事件,因为这是通知对象属性更新的常见方式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接