C# 更新对象并将其从 MainForm 传递到已打开的 childForm

C# Update and pass object from MainForm to already opened childForm

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

我的对象:

 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
    }

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

您可以使用 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)
     {
          .....
     }

}