views:

74

answers:

2

Hello!

I'm developing a Windows Mobile 5.0 or above application with .Net Compact Framework 2.0 SP2 and C#.

I have a Winform (Form1) with a control (Control1) that contains another control (Control2). For example, a winform with a panel and inside this panel there is a button, but in my case Control1 and Control2 are custom controls.

Control2 has an event, Click, that is thrown when the user does click over it. This click event must be handled by Form1. To do it, first I handle the event on Control1 that throws a new event that is handled on Form1. This my code:

On Control1:

public event EventHandler Control2Click;

private void control2_Click(object sender, EventArgs e)
{
    if (Control2Click != null)
    {
        Control2Click(sender, e);
    }
}

On Form1:

private void control1_Control2Click(object sender, EventArgs e)
{
    // Do something interesting.
}

Is there a better way to handle Control2_Click directly in Form1? I don't know if my way has a bad performance and this kind of events can be handled better.

Thank you!

A: 

What's stopping you from hooking up the Control2 Click event directly from Form1? Does Control1 expose Control2 via a property? Or perhaps expose an event on Control1 which actually hooks up to the Control2 Click event? For example:

// In Control1
// Assuming Control2 is some sort of Save button, for example
public EventHandler SaveClicked
{
    add { control2.Click += value; }
    remove { control2.Click -= value; }
}

Note that:

  • If you change the value of control2 within Control1, the event handlers won't be "transferred" which would be be unfortunate
  • The sender parameter in the event handler will refer to Control2, not Control1

To be honest I wouldn't expect this to be a performance problem however you handle it - it's just a delegate invocation or two.

Jon Skeet
+2  A: 

No, you are doing it right. It is the correct way the bubble an event out of a nested control that isn't directly accessible from a container control. You'd normally use the PerformClick() method to fire the Click event but this doesn't appear to be available in CF.

Perf is not an issue, calling a delegate target is very fast, a dozen nanoseconds or so on a desktop machine. Click is a "human-time" event, anything less than 20 milliseconds is perceived as "instant".

Hans Passant