我需要比您通过 ShowDialog 获得的传统 OK 或 Cancel 状态更多的信息,即我的自定义对话框表单上的文本框中的一些字符串。
我想知道这是什么逻辑。我想这样调用它:
CustomDialog d = new CustomDialog();
DoStuffWith(d.ShowDialog().CustomString);
当然,返回结果还得有一个自定义类。让我们这样定义它:
class CustomDialogResult
{
public string CustomString { get; private set; }
public CustomDialogResult(string customString)
{
this.CustomString = customString;
}
}
然后我们需要在我们的 CustomDialog : Form 中重新验证 ShowDialog 方法。我猜我们可以从表单的一些父级显示开始。此外,将事件处理程序添加到 OK 按钮,这将设置一个结果。
public CustomDialogResult CustomDialogResult { get; private set; }
private void buttonOK_Click(object sender, EventArgs e)
{
this.Result = new CustomDialogResult(this.TextBoxCustom.Text);
this.Close();
}
public CustomDialogResult ShowCustomDialog()
{
this.Show(Form.ActiveForm);
}
如您所见,问题在于等待 OK 按钮被单击,然后返回 this.Result。我可以使用 Thread.Sleep(0) 或 ManualResetEvent,但这会阻止对话框表单上的输入。我将如何处理这个问题?我知道我可以使用更丑陋的语法,但如果 ShowDialog 做得很好,我们就必须有办法。 :)
最佳答案
考虑 OpenFileDialog .
它使用标准的 OK 结果,并通过属性和方法简单地公开额外信息。
要自己执行此操作,您只需设置确定按钮的 DialogResult到 DialogResult.OK,然后您的调用表单将通过属性或方法询问您的额外信息。
所以调用代码是这样的
CustomDialog d = new CustomDialog();
if(d.ShowDialog() == DialogResult.OK)
{
CustomDialogResult foo = d.CustomDialogResult;
DoStuff(foo.CustomString);
}
关于c# - 比 DialogResult 包含更多信息的自定义 ShowDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5774408/