如何在带有C#的Windows窗体对话框中实现“应用”按钮操作?
答案 0 :(得分: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..
}
答案 1 :(得分:1)
您可以将表单的AcceptButton-Property设置为表单上的任何按钮。当在表单上按下“Enter”键时,将引发AcceptButton的Click-Event。
也许这就是你要找的东西。
答案 2 :(得分:1)
在Windows中,“应用”按钮通常设置用户在对话框中指定的任何属性,而不用关闭对话框。所以它基本上与除了没有关闭对话框的命令外,单击“确定”按钮。
您可以利用这一事实并合并Apply按钮的事件处理程序中的所有属性设置代码,然后在单击“确定”按钮时,在关闭表单之前调用该代码:
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;
}