简体   繁体   中英

Event sender from custom control

I have a control which extends UserControl . This control contains two ComboBox controls. I've created an event handler which fires when either of the combos changes:


public event EventHandler ComboChanged
{
add { cmbA.SelectedIndexChanged += value; cmbB.SelectedIndexChanged += value; }
remove {...}
}

When I add an event handler to this event, is there any way for the sender to be reported as the custom control (ie the ComboBox's parent control) rather than the ComboBox itself? Or am I trying to do something I shouldn't be doing here?

You should have something like this :

public event EventHandler MyControlChanged

and then in your userControl two functions for each of the ComboBox

protected void oncmbA_SelectedIndexChanged(object sender, EventArgs e)
{
   if (MyControlChanged!=null)
     MyControlChanged(this, e);//or some new Eventagrs that you wish to communicate
}

protected void oncmbB_SelectedIndexChanged(object sender, EventArgs e)
{
   if (MyControlChanged!=null)
     MyControlChanged(this, e);//or some new Eventagrs that you wish to communicate
}

this would then refer to the UserControl and not to the combobox that fired your UserControl's event.

Yoann's answer is the way to go. Here's a similar pattern, but with some minor differences.

// Default listener makes null-check unnecessary when raising event.
// Note that no custom implementations are provided for add, remove.
public event EventHandler ComboChanged = delegate { };

...

foreach(var comboxBox in new[] {cmbA, cmbA})
{
  // Attach listener to combo-box's event that raises our own event.
  // Lambda-expression is ok since we don't intend to ever unsubscribe.
  comboBox.SelectedIndexChanged += (sender, args) => ComboChanged(this, args);
}

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