使用委托和事件从另一个表单更新表单 [英] Update form from another form using delegate and event

查看:106
本文介绍了使用委托和事件从另一个表单更新表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直忘记这样做是怎么做到的。

I keep forgetting how this is done..

我想从Form2更新主窗体上的UI,而无需创建该窗体的实例。

我记得使用了一个委托/事件,并可能以某种方式传递了第一种形式的实例,但是完全空白了。

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.

帮帮我,谢谢。

从Form2向Form1上的listBox1添加内容。

Add something to listBox1 on Form1 from Form2.

推荐答案

是的,委托和事件是正确的关键字

Yes, delegate and event are correct key words

在某个地方实现EventArgs类:

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

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

在Form1中:

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

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

这篇关于使用委托和事件从另一个表单更新表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆