Propagating events from one Form to another Form in C#

后端 未结 3 2101
心在旅途
心在旅途 2020-12-06 03:14

How can I click a Button in one form and update text in a TextBox in another form?

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 03:55

    Assuming WinForms;

    If the textbox is bound to a property of an object, you would implement the INotifyPropertyChanged interface on the object, and notify about the value of the string being changed.

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

    With the above, if you bind to the Title property - the update will go through 'automatically' to all forms/textboxes that bind to the object. I would recommend this above sending specific events, as this is the common way of notifying binding of updates to object properties.

提交回复
热议问题