【问题标题】:Custom ShowDialog with more information than DialogResult具有比 DialogResult 更多信息的自定义 ShowDialog
【发布时间】:2011-04-25 09:40:28
【问题描述】:

我需要比您通过 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 做得很好,我们必须有一种方法。 :)

【问题讨论】:

    标签: c# .net forms showdialog


    【解决方案1】:

    考虑OpenFileDialog

    它使用标准的OK结果,并通过属性和方法简单地暴露额外的信息。

    要自己执行此操作,您只需将 Ok 按钮的 DialogResult 设置为 DialogResult.OK,然后您的调用表单将通过属性或方法询问您的额外信息。

    所以调用代码是这样的

      CustomDialog d = new CustomDialog();
    
      if(d.ShowDialog() == DialogResult.OK)
      { 
          CustomDialogResult foo = d.CustomDialogResult;
          DoStuff(foo.CustomString); 
      }
    

    【讨论】:

    • 天啊!太简单。现在肯定会这样做。谢谢。
    【解决方案2】:

    您可以在您的 ShowCustomDialog() 方法中封装对 ShowDialog() 的调用。这样,您就可以免费获得它的所有“魔力”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-07
      • 2017-04-11
      • 2017-04-30
      • 2017-04-17
      • 1970-01-01
      • 2013-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多