我正在构建一个包含很多动态元素的 WinForm,我认为我在嵌套控件中的父/子关系方面遇到了一些问题。我能找到的所有现有问题似乎都是 WebForms 独有的,它并不完全有用。
我在定制控件方面也遇到了一些麻烦,但这可能是一个相关的问题。
我试图显示一些 PictureBoxes,每个都有一些相关的 NUD。我最初是通过手工制作大量控件来做到这一点的,但现在我想自动化这个过程并在其他地方重用代码。
实际代码比这复杂一点,但这里是 PseudoCode 和实际代码混合的重要部分
panel_book.Controls.Clear();
for (loop controls)
{
//INITIALIZE CHILD CONTROLS
PictureBox tempBox = new PictureBox();
NumericUpDown t1 = new NumericUpDown();
NumericUpDown t2 = new NumericUpDown();
NumericUpDown t3 = new NumericUpDown();
NumericUpDown t4 = new NumericUpDown();
tempBox.Image = getImage();
tempBox.Size = tempBox.Image.Size;
tempBox.Tag = getValue();
//THIS IS WHAT IS GIVING ME TROUBLE
//=======================================================
tempBox.MouseEnter += new EventHandler(Binder_MouseEnter);
tempBox.Click += new EventHandler(smallCardNew_Click);
//THINGS I'VE TRIED
tempBox.BringToFront();
tempBox.Focus();
t1.Size = new Size();
t2.Size = t1.Size; t3.Size = t1.Size; t4.Size = t1.Size;
t1.Location = new Point();
t2.Location = new Point(); t3.Location = new Point(); t4.Location = new Point();
t1.Value = 0;
t2.Value = 0; t3.Value = 0; t4.Value = 0;
t1.Enabled = true; t2.Enabled = true;
t3.Visible = false; t4.Visible = false;
//CREATE THE NEW PARENT CONTROL (PANEL)
Panel tempPanel = new Panel();
tempPanel.Margin = new Padding(0, 0, 0, 0);
tempPanel.Controls.Add(tempBox);
tempPanel.Controls.Add(t1);
tempPanel.Controls.Add(t2);
tempPanel.Controls.Add(t3);
tempPanel.Controls.Add(t4);
tempPanel.Size = new Size();
tempPanel.Location = new Point();
panel_book.Controls.Add(tempPanel);
}//end loop
///
void smallCardNew_Click(object sender, EventArgs e)
{
MessageBox.Show("Click Event Triggered");
}
void Binder_MouseEnter(object sender, EventArgs e)
{
MessageBox.Show("Mouse Enter Event Triggered");
}
希望这很清楚,以防万一它很重要,这里有更多背景。
我有一个非常大的 FlowLayoutPanel,其中包含一些子面板。其中一个子面板是我现在正在研究的领域。(上面称为 panel_book) 该面板是我动态添加带有 PictureBox 和朋友的子面板的内容。
烦人的是,那些 MouseEnter 和 Click 事件没有被触发。完全没有。我之前在运行时添加了事件处理程序,当时控件不是动态的,并且从未遇到过这么多麻烦。我很确定我什至也使用嵌套控件做到了这一点。
最后,我考虑过将最后一个子面板变成它自己的自定义控件,但也遇到了类似的问题。大概找到解决此问题的方法也可以解决该问题,但是如果您知道不会,请您指出正确的方向吗?
谢谢, :)