如何以编程方式调用 TextBox 的 Click 事件处理程序
How to programmatically invoke the Click event handler of a TextBox
我知道如何以编程方式调用按钮的事件处理程序:
button1.PerformClick();
我想对 TextBox
的 Click
事件处理程序执行相同的操作。问题是 TextBox 没有
textBox1.PerformClick();
我建议方法提取(为什么我们要混合UI - windows消息和业务逻辑):
//TODO: put a better name here
private void onMyTextBoxClick() {
//TODO: relevant code here
}
private void MyTextBox_Click(object sender, EventArgs e) {
onMyTextBoxClick();
}
然后你可以调用 onMyTextBoxClick
:
...
// Same business logic as if MyTextBox is clicked
onMyTextBoxClick();
...
编辑: 如果你真的想要 EventArgs
装备,只需提供它们:
//TODO: put a better name here
private void onMyTextBoxClick(TextBox box, EventArgs e) {
//TODO: relevant code here
}
// Default EventArgs
private void onMyTextBoxClick(TextBox box) {
onMyTextBoxClick(box, EventArgs.Empty);
}
// Both TextBox and EventArgs are default ones
private void onMyTextBoxClick() {
onMyTextBoxClick(MyTextBox, EventArgs.Empty);
}
private void MyTextBox_Click(object sender, EventArgs e) {
onMyTextBoxClick(sender as TextBox, e);
}
用法:
// Default EventArgs
onMyTextBoxClick(myTextBox);
// Custom EventArgs
EventArgs args = ...
onMyTextBoxClick(myTextBox, args);
我知道如何以编程方式调用按钮的事件处理程序:
button1.PerformClick();
我想对 TextBox
的 Click
事件处理程序执行相同的操作。问题是 TextBox 没有
textBox1.PerformClick();
我建议方法提取(为什么我们要混合UI - windows消息和业务逻辑):
//TODO: put a better name here
private void onMyTextBoxClick() {
//TODO: relevant code here
}
private void MyTextBox_Click(object sender, EventArgs e) {
onMyTextBoxClick();
}
然后你可以调用 onMyTextBoxClick
:
...
// Same business logic as if MyTextBox is clicked
onMyTextBoxClick();
...
编辑: 如果你真的想要 EventArgs
装备,只需提供它们:
//TODO: put a better name here
private void onMyTextBoxClick(TextBox box, EventArgs e) {
//TODO: relevant code here
}
// Default EventArgs
private void onMyTextBoxClick(TextBox box) {
onMyTextBoxClick(box, EventArgs.Empty);
}
// Both TextBox and EventArgs are default ones
private void onMyTextBoxClick() {
onMyTextBoxClick(MyTextBox, EventArgs.Empty);
}
private void MyTextBox_Click(object sender, EventArgs e) {
onMyTextBoxClick(sender as TextBox, e);
}
用法:
// Default EventArgs
onMyTextBoxClick(myTextBox);
// Custom EventArgs
EventArgs args = ...
onMyTextBoxClick(myTextBox, args);