简体   繁体   English

AcceptButton不会关闭表格

[英]AcceptButton won't close form

I have two forms that are very similar, but in one of them clicking the AcceptButton closes the form, and in the other it doesn't close the form. 我有两个非常相似的表单,但是其中一个单击AcceptButton关闭该表单,而在另一个中,它不会关闭该表单。 Both of them have their AcceptButton set to btnAccept . 他们两个的AcceptButton设置为btnAccept

I recently created the second one, the first one has existed for awhile and was created by someone else. 我最近创建了第二个,第一个已经存在了一段时间,并且是由其他人创建的。

They are both opened this way: 它们都以这种方式打开:

using(var form = new SomeDialog(dependency))
{
    form.StartPosition = FormStartPosition.CenterParent;
    form.ShowDialog(this);
}

Both of them handle the accept button click along these lines. 他们两个都沿着这些行处理接受按钮单击。

private void btnAccept_Click(object sender, EventArgs e)
{
  _dependency.DoSomething(userInput);
}

Posting my entire designer file probably wouldn't be helpful. 发布我的整个设计器文件可能不会有帮助。 Is there something in particular that'd be helpful to show from it? 有什么特别的东西可以从中显示出来吗? I couldn't find a similar post on StackOverflow. 我在StackOverflow上找不到类似的帖子。

What am I missing that's causing the divergent behavior? 我在想什么导致行为差异?

The AcceptButton property just selects the button that will implement the default action when you press the Enter key. AcceptButton属性仅选择按Enter键时将执行默认操作的按钮。 Clearly visible in the UI with a heavy border around the button. 在用户界面中清晰可见,按钮周围带有粗边框。 But that isn't enough, you still have to implement the default action. 但这还不够,您仍然必须实施默认操作。

A simple way is to set the button's DialogResult property in the designer. 一种简单的方法是在设计器中设置按钮的DialogResult属性。 Which is okay but tends to cause surprises when your event handler does something like validate the dialog content, you'd have to set the form's DialogResult property back to None when you're not happy. 没关系,但是当事件处理程序执行诸如验证对话框内容之类的操作时,往往会引起意外,您不满意时必须将窗体的DialogResult属性设置回None。 I personally prefer to always set the form's DialogResult explicitly in the Click event handler. 我个人更喜欢始终在Click事件处理程序中显式设置表单的DialogResult。 That's debuggable code, let's me see why it "doesn't work". 那是可调试的代码,让我看看为什么它“不起作用”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM