2010-12-15 61 views

回答

2

Windows窗体不会让它变得特别容易,除非它是对话本身照顾副作用。这并不总是常见的,它通常以调用ShowDialog()的形式完成,基于返回值。

没什么大不了的,虽然,自己的事件添加到窗体:

public event EventHandler ApplyChanges; 
    protected virtual void OnApplyChanges(EventArgs e) { 
     var handler = ApplyChanges; 
     if (handler != null) handler(this, e); 
    } 

    private void OKButton_Click(object sender, EventArgs e) { 
     OnApplyChanges(EventArgs.Empty); 
     this.DialogResult = DialogResult.OK; 
    } 

    private void ApplyButton_Click(object sender, EventArgs e) { 
     OnApplyChanges(EventArgs.Empty); 
    } 

,然后在主窗体的代码看起来是这样的:

private void ShowOptionsButton_Click(object sender, EventArgs e) { 
     using (var dlg = new Form2()) { 
      dlg.ApplyChanges += new EventHandler(dlg_ApplyChanges); 
      dlg.ShowDialog(this); 
     } 
    } 

    void dlg_ApplyChanges(object sender, EventArgs e) { 
     var dlg = (Form2)sender; 
     // etc.. 
    } 
+0

+1关于它的好处通常不是对话本身,它负责其副作用。如果你的情况不像我想的那么简单,这可能是更优雅的解决方案。 – 2010-12-15 16:22:46

1

您可以将表单的AcceptButton-Property设置为放置在表单上的任何按钮。当在表单上按下“Enter”键时,会引发AcceptButton的Click事件。

也许这就是你要找的。

1

在Windows中,“应用”按钮通常设置用户在对话框中指定的任何属性,而不用关闭对话框。所以它与“OK”按钮基本相同,除非没有关闭对话框的命令。

你可以利用这一事实,并整合所有的财产设定的代码在应用按钮的事件处理程序,那么首先调用只要单击OK按钮,但你关闭窗体之前:

public void ApplyButtonClicked(object sender, EventArgs e) 
{ 
    //Set any properties that were changed in the dialog box here 
    //... 
} 

public void OKButtonClicked(object sender, EventArgs e) 
{ 
    //"Click" the Apply button, to apply any properties that were changed 
    ApplyButton.PerformClick(); 

    //Close the dialog 
    this.DialogResult = DialogResult.OK; 
}