事件回调

既然C#有事件这个东西,为啥不用呢,而且事件在窗体通信方面,有着更为方便的作用,我们知道事件实际上就是状态的捕获,在最后我会举一个捕获状态的例子,先看数据互相操作的例子。
    Form2:

//定义一个需要string类型参数的委托

public delegate void MyDelegate(string text);

public   {

        //定义该委托的事件
        public event MyDelegate MyEvent;
        public Form2(string text)
        {
            InitializeComponent();
            this.textBox1.Text = text;
        }
        private void btnChange_Click(object sender, EventArgs e)
        {

            //触发事件,并将修改后的文本回传
            MyEvent(this.textBox1.Text);
            this.Close();
        }

    }

    Form1:

public   {
        public int index = 0;
        public string text = null;
        public Form1()
        {
            InitializeComponent();
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listBox1.SelectedItem != null)
            {
                text = this.listBox1.SelectedItem.ToString();
                index = this.listBox1.SelectedIndex;
                Form2 form2 = new Form2(text);

                //注册form2_MyEvent方法的MyEvent事件
                form2.MyEvent += new MyDelegate(form2_MyEvent);
                form2.Show();
            }
        }

        //处理

        void form2_MyEvent(string text)
        {
            this.listBox1.Items.RemoveAt(index);
            this.listBox1.Items.Insert(index, text);
        }
    }

    可以看出,使用事件做是很方便的,并且不需要传递那么多参数,不需要有继承关系,且提高了代码重用,因此在一般的需求下,建议这么使用。最后说一下事件的状态捕获。
    窗体:
   
----------------------------------------------------------------------
   
    当点Form1中的ShowForm2按钮时,弹出Form2,且在TextBox里写入"Show Form2",当点Form2中Form2Close按钮时,关闭Form2,且将Form1的TextBox文本改为"Close Form2",这就是一个状态的捕获过程,常用在应用程序的状态栏。
    Form1:

public   {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            this.textBox1.Text = "Show Form2";
            form2.MyEvent += new EventHandler(form2_MyEvent);
            form2.Show();
        }

        void form2_MyEvent(object sender, EventArgs e)
        {
            this.textBox1.Text = "Close Form2";
        }
    }

    Form2:

public   {
        public event EventHandler MyEvent;
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MyEvent(sender,e);
            this.Close();
        }
    }

    这就是事件在窗体间通讯以及窗体间状态捕获中常用的方法,POST一下,希望没有超字数-__-
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值