C#學習筆記(31)——委託窗體傳值

說明(2017-11-23 19:31:53):函數

1. 關於委託和窗體傳值,一下午在網上查閱了大量資料,基本就是CSDN的論壇和博客園的文章,你們都在舉例子,燒水、鴻門宴,看評論說還看到過沙漠足球的,真是跪了。。this

2. 最後仍是看一直了CZ楊洪波三層裏的窗體傳值,照着把代碼寫出來的,其實我第一次據說「窗體傳值」這個概念,就是聽得楊洪波講的這個。spa

3. 最關鍵的一步,就是把字符串和方法,做爲Form2的參數,傳給Form2。code

4. 雖然前面作了好幾個委託的例子,也知道委託怎麼寫,可是這個傳值就是不知道怎麼寫,一開始一直覺得要把委託寫在Form1裏,誰知道是寫在Form2裏的!orm

5. 蔣坤是讓寫一個點擊改變Form1的背景顏色,應該比窗體傳值簡單,或者說是一個套路,我試一下。blog

Form1:繼承

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace _07_窗體傳值
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2(tb1.Text, DoSth);
            f2.Show();
        }
        //這個方法經過Form2的構造函數傳過去
        public void DoSth(string str)
        {
            tb1.Text = str;
        }

    }
}

Form2:字符串

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace _07_窗體傳值
{
    //委託要定義在Form2裏面
    public delegate void MyDel(string str);
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();

        }
        //聲明一個委託變量,接收Form2傳過來的委託
        private MyDel _mdl;
        //精髓就在於Form2的構造函數,把Form1的值和DoSth方法傳到Form2裏面,this是爲了繼承Form2窗體,省去了InitializeComponent()這一行
        public Form2(string str, MyDel mydel)
            : this()
        {
            tb2.Text = str;
            this._mdl = mydel;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //調用委託以前必定要判斷委託是否爲空
            if (_mdl != null)
            {
                _mdl(tb2.Text);
                this.Close();
            }
        }

    }
}

效果是這樣嬸兒的:博客

首先:string

其次:

相關文章
相關標籤/搜索