如何编程调用文本框的点击事件处理程序

发布于 2025-01-19 09:10:38 字数 290 浏览 2 评论 0原文

I know how to programmatically invoke the event handler of a Button:

button1.PerformClick();   

I would like to do the same for the Click event handler of a TextBox.问题是文本框没有

textBox1.PerformClick(); 

I know how to programmatically invoke the event handler of a Button:

button1.PerformClick();   

I would like to do the same for the Click event handler of a TextBox. The problem is that TextBox does not have a

textBox1.PerformClick(); 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

兰花执着 2025-01-26 09:10:38

我建议方法提取(为什么我们应该混合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);

I suggest method extraction (why should we mix UI - windows messages and Business Logic):

//TODO: put a better name here 
private void onMyTextBoxClick() {
  //TODO: relevant code here
}

private void MyTextBox_Click(object sender, EventArgs e) {
  onMyTextBoxClick();
}

Then you can just call onMyTextBoxClick:

...
// Same business logic as if MyTextBox is clicked
onMyTextBoxClick();
...

Edit: If you really want EventArgs aruments, just provide them:

//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);
}

Usage:

// Default EventArgs
onMyTextBoxClick(myTextBox);

// Custom EventArgs
EventArgs args = ...

onMyTextBoxClick(myTextBox, args);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文