开发者

Event sender from custom control

开发者 https://www.devze.com 2023-01-23 05:52 出处:网络
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:

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 += valu开发者_如何学运维e; }
remove {...}
}

When I add an event handler to this event, is there any way for the sender to be reported as the custom control (i.e. 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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消