c# - 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
}
有什么解决办法吗?谢谢你。
解决方案
您可以使用 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)
{
.....
}
}
推荐阅读
- javascript - 为什么我收到 TypeError 无法读取我定义的数组和对象的未定义属性“移动”?
- postgresql - 在 postgresql 中访问复合数组的属性值的问题
- python - 自引用不适用于 Flask (SQLAlchemy)
- php - PHP $_POST 数组
- javascript - 当它会导致错误时如何禁用“背景附件:已修复”
- json - 在 lua 中创建 Json 对象
- cmake - cmake 3.15 adding JOB_POOL to add_custom_command SOMETIMES
- jenkins - 为什么我不能在与主机(Windows 10)相同的机器上设置詹金斯代理,詹金斯在本地主机上?
- javascript - toggleClass - localStorage 在第一次加载页面时从某些元素中删除所有类。如何解决?
- python - 在列表中解压迭代器的 Pythonic 方法