我希望我的容器是由它所包含的控件触发的事件的发送者
本文关键字:控件 发送者 事件 包含 我的 我希望 | 更新日期: 2023-09-27 18:00:04
下面的代码有效,但我需要发件人是SpecialTextBox,而不是SpecialTextBox中的TextBox。原因是我需要从SpecialTextBox中获取"IdCode",当它是TextBox时。触发休假事件。
这样一来,发件人似乎就是SpecialTextBox中的TextBox。
希望这有意义。。。
我的面板将包含文本框。。。
class BigPanel: Panel
{
SpecialTextBox stb = new SpecialTextBox();
public BigPanel()
{
BorderStyle = BorderStyle.FixedSingle;
stb.SpecialTBLeave += Stb_SpecialTBLeave;
Controls.Add(stb);
}
private void Stb_SpecialTBLeave(object sender, EventArgs e)
{
SpecialTextBox s = (sender as SpecialTextBox);
}
}
我的"特殊"文本框我删除了大部分功能,以保持示例的简单性。
class SpecialTextBox : Panel
{
TextBox tb = new TextBox();
public string IdCode {get; set;}
public SpecialTextBox()
{
Controls.Add(tb);
BorderStyle = BorderStyle.FixedSingle;
Left = 30;
}
public event EventHandler SpecialTBLeave
{
add { this.tb.Click += value; }
remove { this.tb.Click -= value; }
}
}
我的主表单上的代码…
BigPanel bp = new BigPanel();
Controls.Add(bp);
您需要在SpecialTextBox
内部处理内部TextBox
的事件,并提供要从外部消耗的新事件:
class SpecialTextBox : Panel
{
TextBox tb = new TextBox();
public string IdCode {get; set;}
// simple event, don't register to the inner TextBox!
public event EventHandler SpecialTBLeave;
public SpecialTextBox()
{
Controls.Add(tb);
BorderStyle = BorderStyle.FixedSingle;
Left = 30;
// register to inner TextBox' event to raise outer event
tb.Leave += (sender, e) => SpecialTBLeave?.Invoke(this, e);
}
}
由于您继承自Panel
,因此可以考虑使用Panel
的现有Leave
事件,而不是创建一个新事件:
public SpecialTextBox()
{
tb.Leave += (sender, e) => base.OnLeave(e);
}