c# 使用委托子窗体改变父窗体控件

首先创建两个窗体,在窗体1和窗体2放上对应的控件

在窗体1的代码如下

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 委托改变控件值
{
    public delegate void MyDel();
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {
        public static MyDel myDel;//定义一个委托类型的变量
        public static string str;//定义一个静态类型的字段
        public Form1()
        {
            InitializeComponent();
            myDel = new MyDel(Change);
        }
        /// <summary>
        /// 更改值
        /// </summary>
        public void Change()
        {
            label1.Text = str;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Form2 fom = new Form2();
            fom.ShowDialog();
        }
    }
}

窗体2的代码

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 委托改变控件值
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //把值传递到父窗体
            Form1.str = textEdit1.Text;
            //调用委托
            Form1.myDel();
        }
    }
}

窗体1的lab根据窗体而的文本框而改变

demo下载链接https://download.csdn.net/download/qq_38977099/10872406