我有一个父表单和一个对话框。我需要将信息从父级传递到对话框
这就是我所拥有的:
private void Item_Click(object sender, EventArgs e)
{
DialogResult result = DialogResult.OK;
DlgGraphOptions _frmDlgGraphOptions = new DlgGraphOptions();
_frmDlgGraphOptions.m_SerOpts = theDGroup.m_SerOpts;
_frmDlgGraphOptions.ShowDialog(this);
if (result == DialogResult.OK)
{
// Save the revised options to the Data Group
theDGroup.m_SerOpts = _frmDlgGraphOptions.m_SerOpts;
}
在DlgGraphOptions(子/对话框)表单中,我已经初始化了
public partial class DlgGraphOptions : Form
{
public GraphOpts_t m_SerOpts = new GraphOpts_t();
}
private void InitSettings(int idxSeries)
{
m_nMaxPts = m_SerOpts.GetMaxPts(idxSeries);
}
所以我需要将父组的DGroup.m_SerOpts传递给对话框,所以我已经完成了
_frmDlgGraphOptions.m_SerOpts = theDGroup.m_SerOpts;
父母中的。现在在孩子身上:
public GraphOpts_t m_SerOpts = new GraphOpts_t;
这似乎是错误的。我不想重新初始化它。
答案 0 :(得分:1)
我认为您应该以这种方式更改您的代码:
首先,在 DlgGraphOptions 表单中,更改DlgGraphOptions的构造函数
// Force the caller to pass a GraphOpts_t
// Check if it is a valid instance or create one as new
public partial class DlgGraphOptions(GraphOpts_t input ) : Form
{
m_SerOpts = (input == null ? new GraphOpts_t() : input);
}
然后创建一个公共属性,只有getter返回内部GraphOpts
public GraphOpts_t Options
{
get{ return m_SerOpts; }
}
然后,在调用表单中,更改您的代码
// Pass the m_setOpts from theDGroup
DlgGraphOptions _frmDlgGraphOptions = new DlgGraphOptions(theDGroup.m_SerOpts);
if(DialogResult.OK == _frmDlgGraphOptions.ShowDialog(this))
{
// Save the revised (or new) options to theDGroup
theDGroup.m_SerOpts = _frmDlgGraphOptions.Options;
}
此方法将强制对话框的用户传递初始化值或null。 但是,您的InitSettings将使用初始值,并且您没有初始化两次您的选项实例 (实际上你的代码没有很大的改进,但我认为这是一种更好的方法)
答案 1 :(得分:0)
您的子课可能应该将m_SerOpts
作为财产:
public partial class DlgGraphOptions : Form
{
public GraphOpts_t m_SerOpts { get; set; }
}
您的点击事件可能会像这样清除:
private void Item_Click(object sender, EventArgs e)
{
using (DlgGraphOptions _frmDlgGraphOptions = new DlgGraphOptions()) {
_frmDlgGraphOptions.m_SerOpts = theDGroup.m_SerOpts;
if (_frmDlgGraphOptions.ShowDialog(this) == DialogResult.OK)
{
// Save the revised options to the Data Group
theDGroup.m_SerOpts = _frmDlgGraphOptions.m_SerOpts;
}
}
}
在DlgGraphOptions表单中,您需要在DialogResult
或OK
按钮事件中设置表单的Save
属性。
您也可以通过构造函数传递m_SerOpts对象:
public partial class DlgGraphOptions : Form
{
public GraphOpts_t m_SerOpts { get; }
public DlgGraphOptions(GraphOpts_t serOpts) {
InitializeComponents();
m_SerOpts = serOpts;
}
}