You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WinForm用户控件间如何传递值并修改文本框内容

看起来你现在的问题出在实例不匹配上——你在Burger里新建了一个mol对象,但这个对象和你界面上实际显示的mol控件不是同一个实例,所以你设置的属性和调用的方法根本不会作用到界面上的控件。下面给你几种实用的解决方案,从简单到推荐的低耦合方式:

方案1:直接获取父窗体上的目标控件实例

如果两个用户控件都放在同一个父窗体上,可以通过父窗体找到界面上真实存在的mol实例:

首先完善mol的属性(你之前的代码没写完):

public partial class mol : UserControl { 
    public string sou { 
        set { 
            textBox1.Text = value; // 补全属性赋值逻辑
        }
    }

    public void my(int value) {
        // 这里实现你需要的方法逻辑,比如处理传入的数值
    }
}

然后修改Burger的点击事件代码:

public partial class Burger : UserControl { 
    public int t_num_Z_bur = 0; 
    public int t_num_B_bur = 0; 

    private void button1_Click(object sender, EventArgs e) { 
        t_num_Z_bur++; 
        textBox1.Text = t_num_Z_bur.ToString(); 

        // 从父窗体中找到mol控件实例
        var targetMol = this.Parent.Controls.OfType<mol>().FirstOrDefault();
        if (targetMol != null) {
            targetMol.sou = "180";
            targetMol.my(180);
        }
    } 
}

这种方式简单直接,但耦合度较高,适合小型项目或快速原型开发。

方案2:使用事件委托(推荐,低耦合)

这种方式遵循面向对象的设计原则,Burger只负责触发事件,不用关心谁来处理,扩展性更好:

首先在Burger中定义事件:

public partial class Burger : UserControl { 
    public int t_num_Z_bur = 0; 
    public int t_num_B_bur = 0; 

    // 定义事件,传递需要的数据(这里用Action<string, int>封装要传递的两个值)
    public event Action<string, int> OnBurgerUpdated;

    private void button1_Click(object sender, EventArgs e) { 
        t_num_Z_bur++; 
        textBox1.Text = t_num_Z_bur.ToString(); 

        // 触发事件,传递数据(用?.避免空引用)
        OnBurgerUpdated?.Invoke("180", 180);
    } 
}

然后在父窗体中绑定事件处理逻辑,找到mol控件并更新:

public class YourParentForm : Form {
    public YourParentForm() {
        InitializeComponent();
        
        // 假设你的Burger控件名为burger1,mol控件名为mol1
        burger1.OnBurgerUpdated += Burger1_OnBurgerUpdated;
    }

    private void Burger1_OnBurgerUpdated(string souValue, int myValue) {
        // 更新mol控件的内容
        mol1.sou = souValue;
        mol1.my(myValue);
    }
}

mol的代码和方案1一样完善即可。这种方式的优势是,以后如果有其他控件需要响应Burger的操作,只需要绑定事件就行,不需要修改Burger的代码。

方案3:通过属性传递目标控件实例

在Burger中添加一个属性,直接接收界面上的mol实例:

public partial class Burger : UserControl { 
    public int t_num_Z_bur = 0; 
    public int t_num_B_bur = 0; 

    // 添加属性,用于接收mol控件实例
    public mol TargetMol { get; set; }

    private void button1_Click(object sender, EventArgs e) { 
        t_num_Z_bur++; 
        textBox1.Text = t_num_Z_bur.ToString(); 

        if (TargetMol != null) {
            TargetMol.sou = "180";
            TargetMol.my(180);
        }
    } 
}

然后在父窗体的初始化代码中,给Burger的属性赋值:

public YourParentForm() {
    InitializeComponent();
    // 将界面上的mol实例传给Burger
    burger1.TargetMol = mol1;
}

这种方式耦合度介于前两者之间,适合中等复杂度的场景。

内容的提问来源于stack exchange,提问作者Nauman Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:04:47