首页 > 解决方案 > C# 更新并将对象从 MainForm 传递到已打开的 childForm

问题描述

我有 5 种不同的形式。第一种形式是 MainForm,其他形式是 childForms。
MainForm 具有我可以随时更改的参数,并且子表单具有从 mainform 获取对象的不同任务。
如何将该对象从 mainform 传递然后更新为 childforms ?我找到了带有事件的解决方案,但它从子窗体更新了主窗体。这里

我的对象:

 public class BarcodeModel
{
    public string XCoord { get; set; }
    public string YCoord { get; set; }
    public bool IsRequired{ get; set; }
}

主窗体:

  private void btnOneFile_Click(object sender, EventArgs e)
    {
        Form1File newForm = new Form1File();
        BarcodeModel model = new BarcodeMode();
        OpenChildForm(newForm, sender);
    }

  private void comboBoxClients_SelectedIndexChanged(object sender, EventArgs e)
    {
       model.XCoord = "DynamicInfo";
       model.YCoord = "DynamicInfo";
       model.IsRequired = true;
       // every time it changes I want to send data to child form
    }

子窗体:

private void btnStart1File_Click(object sender, EventArgs e)
    {
        // here I want to have updated object
    }

有什么解决办法吗?谢谢你。

标签: c#winformsevents

解决方案


您可以使用 MainForm 引发的自定义事件。因此,每个有兴趣了解 Barcode 模型更改并具有对 MainForm 的实例引用的客户都可以订阅该事件并接收由 MainForm 处理的 Barcode 实例的更新版本。

在主窗体中声明自定义事件,以便任何人都可以订阅它

public delegate void ModelChangedHandler(Barcode model);
public event ModelChangedHandler BarcodeChanged;

现在,当您更改模型属性时,仍会在 MainForm 中引发事件。

private void comboBoxClients_SelectedIndexChanged(object sender, EventArgs e)
{
   model.XCoord = "DynamicInfo";
   model.YCoord = "DynamicInfo";
   model.IsRequired = true;
   BarcodeChanged?.Invoke(model);
}

在子窗体中,您需要有一个构造函数来接收 MainForm 实例并将其保存到内部属性中。同时,您使用子表单内部的处理程序订阅事件

public class Form1File : Form
{
     MainForm _parent = null;
     public Form1File(MainForm main)
     {
         _parent = main;
         _parent.BarcodeChanged += modelChanged;
     }

处理程序接收更新的模型并使用新模型信息执行所需的操作

     public void modelChanged(Barcode model)
     {
          .....
     }

}

推荐阅读