如何在一个窗体中点击按钮并更新另一个窗体中的文本框?
如果您正在尝试使用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...";
}
}
假设使用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属性,则更新将“自动”传递到绑定到该对象的所有表单/文本框。我建议使用此方法而不是发送特定事件,因为这是通知对象属性更新的常见方式。