简体   繁体   中英

C# Passing controls around and maintaining events

Say I have a Form which we'll call it ParentForm , and it contains a Panel which we'll call ContainerPanel . Now, ContainerPanel contains a Panel , which we'll call EntityPanel .

So basically, the Form contains A Panel which contains a Panel .

In ContainerPanel, we have:

void EntityPanel_MouseDown(object sender, MouseEventArgs e)
{
  ContainerPanel.Controls.Remove(EntityPanel);
  ParentForm.AcceptEntityPanel(EntityPanel);
}

and in MainForm, we have:

void AcceptEntityPanel(Panel panel)
{
  Controls.Add(panel);
  panel.MouseUp += new MouseEventHandler(
    delegate(object sender, MouseEventArgs e)
    {
      MessageBox.Show("Mouse has been released.");
    });
}

Note: This is example code only, which I have just typed in here without verifying syntax, etc. I realise it is trivial to combine these two functions into one, however in my application these two functions do several other things and should be separate.

So the EntityPanel , which belongs to ContainerPanel needs to be transferred to ParentForm when the user presses the mouse down.

When the user releases the mouse, I still need the MouseUp event to be triggered, but it is not working.

Previously , I was passing information about the panel and creating a new panel on the parent form, and manually calling the MouseDown method.

What I'm doing now, as you can see in my above example, is that I'm passing the exact same panel back to the parent form. I had hoped that this way the MouseDown/MouseUp would work, however it didn't.

I'm running out of ideas on how else to structure this module of my program. Any ideas?

This works for me:

 void Form1_Load(object sender, EventArgs e)
 {
    var innerPanel = new Panel();
    outerPanel.Controls.Add(innerPanel);

    innerPanel.MouseDown += (a,b) => 
     { 
       outerPanel.Controls.Remove(innerPanel);
       Controls.Add(innerPanel);
       innerPanel.MouseUp += (x,y) => MessageBox.Show("!");
     };
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM