Update form from another form using delegate and e

2019-06-03 15:12发布

问题:

I keep forgetting how this is done..

I want to update the UI on the main form from Form2 without creating an instance of the form.
I remember using a delegate / event and possibly passing in an instance of the first form somehow, but totally went blank.

Help me out, thanks.

Add something to listBox1 on Form1 from Form2.

回答1:

Yes, delegate and event are correct key words

Implement your EventArgs class somewhere:

public class MyEventArgs : EventArgs
{
    private List<string> EventInfo;
    public MyEventArgs(List<string> strings)
    {
        EventInfo = strings;
    }
    public List<string> GetInfo()
    {
        return EventInfo;
    }
}

In Form2:

public class Form2
{
  public event EventHandler<MyEventArgs> OnMyChange;

  //call it then you need to update:
  if(OnMyChange!= null)
  {
    MyEventArgs e = new MyEventArgs();

    List<string> content = new List<string>();
    content.Add("abc");
    e.EventInfo = content;

    OnMyChange(this, e);
  }
}

In Form1:

Form2 MyForm2 = new Form2();
MyForm2.OnMyChange += MyChanged;

static void MyChanged(object source, MyEventArgs e)
{
    //e.EventInfo will contain list
    Console.WriteLine("changed");
}


回答2:

You cannot update an object that you did not instantiate.

What you can do is either register some function as handler for a change event in form2. If the function is a member of the main form it can then affect the components of that form.

Passing a delegate is basically the same but would allow you to use an arbitrary function of your choosing. Most of the time this is not worth the overhead, though.



回答3:

Its hard to get exactly what you need from the question, but it sounds like you could pass an Action to your form for adding the items. You could change the constructor in Form2 to ensure you always have the callback - e.g.

 private Action<string> addItemsToParent;

 public Form2(Action<string> addItemsToParent)
 {
    this.addItemsToParent = addItemsToParent;
 }

 public void AddItems()
 {
     addItemsToParent("item 1");
 }