我正在尝试制作一个自定义MessageBox。我正在调用一个带有私有构造函数和静态"show"方法的简单表单。它将动态创建一个OK按钮,可能还会创建一个取消按钮,这取决于用户传入的内容。我在创建按钮时创建Click事件处理程序。我想知道的是如何将DialogResult传递回调用者。以下是创建按钮(显示)和事件处理程序的代码。
public static DialogResult Show(string title, string message, ButtonStyle buttonStyle) {
AFGMessageBox box = new AFGMessageBox();
box.Text = title;
box.LblMessage.Text = message;
if (buttonStyle == ButtonStyle.Ok) {
Button okButton = new Button {
Width = 93,
Height = 40,
Location = new Point(x: 248, y: 202),
Text = "OK"
};
okButton.Click += new EventHandler(OkButtonEventHandler);
}
return _result;
}
private static void OkButtonEventHandler(object sender, EventArgs e) {
_result = DialogResult.OK;
}
您甚至不需要处理点击事件。您只需要按照文档中的说明设置您创建的按钮的Button.DialogResult属性
备注
如果此属性的DialogResult设置为None以外的任何值,并且如果父窗体是通过ShowDialog方法显示的,则单击该按钮将关闭父窗体,而无需挂接任何事件。单击按钮时,表单的DialogResult属性将设置为按钮的DialogResult。例如,要创建"是/否/取消"对话框,只需添加三个按钮,并将其DialogResult属性设置为Yes、No和Cancel。
我认为这是不言自明的,但以防万一,这是您的示例代码的修改版本
public static DialogResult Show(string title, string message, ButtonStyle buttonStyle) {
AFGMessageBox box = new AFGMessageBox();
box.Text = title;
box.LblMessage.Text = message;
if (buttonStyle == ButtonStyle.Ok) {
Button okButton = new Button {
Width = 93,
Height = 40,
Location = new Point(x: 248, y: 202),
Text = "OK",
DialogResult = DialogResult.OK
};
box.Controls.Add(okButton);
}
return box.ShowDialog();
}
按如下方式更改方法AFGMessageBox.Show
:
public static DialogResult Show(string title, string message, ButtonStyle buttonStyle) {
AFGMessageBox box = new AFGMessageBox();
box.Text = title;
box.LblMessage.Text = message;
if(buttonStyle == ButtonStyle.Ok) {
Button okButton = new Button {
Width = 93,
Height = 40,
Location = new Point(x: 248, y: 202),
Text = "OK"
};
box.Controls.Add(okButton); // add the button to your dialog!
okButton.Click += (s, e) => { // add click event handler as a closure
box.DialogResult = DialogResult.OK; // set the predefined result variable
box.Close(); // close the dialog
};
}
return box.ShowDialog(); // display the dialog! (it returns box.DialogResult by default)
}