首页 文章

自定义ShowDialog提供的信息比DialogResult更多

提问于
浏览
1

我需要比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);
}

如您所见,问题在于等待单击“确定”按钮,然后返回此结果 . 结果 . 我可以使用Thread.Sleep(0)或ManualResetEvent,但这会阻止对话框窗体上的输入 . 我怎么去这个?我知道我可以使用更丑陋的语法,但如果ShowDialog做得很好,我们必须有办法 . :)

2 回答

  • 3

    考虑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() 的调用 . 这样,你就可以免费得到它所有的"magic" .

相关问题