首页 文章

是否可以为表单重载ShowDialog方法并返回不同的结果?

提问于
浏览
11

EDIT: This method actually works great and I asked it then found the solution later. I added the correct call in the overloaded ShowDialog() method (it's not exacly an overload, or even an override, but it works just the same. My new question is the one at the bottom.

我有一个表单,您可以在其中单击三个按钮之一 . 我已经为返回的结果定义了一个枚举 . 我想打电话:

MyFormResults res = MyForm.ShowDialog();

我可以使用以下代码添加一个新的ShowDialog方法:

public new MyFormResults ShowDialog()
{
    //Show modal dialog
    base.ShowDialog(); //This works and somehow I missed this

    return  myResult; //Form level variable (read on)
}

单击按钮时,我为结果设置了一个表单级变量:

MyFormResults myResult;

private void btn1_click(object sender, EventArgs e)
{
    myResult = MyFormsResults.Result1;
    this.DialogResult = DialogResult.OK; //Do I need this for the original ShowDialog() call?
    this.Close(); //Should I close the dialog here or in my new ShowDialog() function?
}

//Same as above for the other results

我唯一缺少的是显示对话框(模态)的代码,然后返回我的结果 . 没有 base.ShowDialog() 功能,所以我该怎么做?

EDIT: There is a 'base.ShowDialog()' and it works. This is my new question here:

此外,这是完成所有这些的最佳方式吗?为什么?

谢谢 .

4 回答

  • 1

    编辑:改变 ShowDialog() 的功能绝对不是一个好主意,人们希望它返回一个 DialogResult 并显示表单,我建议如下我的建议 . 因此,仍然允许 ShowDialog() 以正常方式使用 .

    您可以在 MyForm 上创建一个静态方法,类似 DoShowGetResult()

    看起来像这样

    public static MyResultsForm DoShowGetResult()
    {
       var f = new MyForm();
       if(f.ShowDialog() == DialogResult.OK)
       {
          return f.Result;   // public property on your form of the result selected
       }
       return null;
    }
    

    然后你可以用它

    MyFormsResult result = MyForm.DoShowGetResult();
    
  • 12

    试试这个,它似乎对我有用:

    public partial class Form2 : Form
        {
            public Form2()
            {
                InitializeComponent();
            }
    
            public DialogResult ShowDialog(string mes)
            {
                this.textBox1.Text = mes;
                return base.ShowDialog();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                this.Close();
            }
        }
    
  • 0

    不,这是不可能的 . 通常的解决方法是将您的真实结果作为表单上的属性公开:

    public MyFormResults MyResult
    {
        get;
    }
    

    然后你会设置这个:

    private void btn1_click(object sender, EventArgs e)
    {
        MyResult = MyFormsResults.Result1;
        this.DialogResult = DialogResult.OK; //Do I need this for the original ShowDialog() call?
        this.Close(); //Should I close the dialog here or in my new ShowDialog() function?
    }
    

    调用代码通常如下所示:

    if (form.ShowDialog == DialogResult.OK)
    {
        //do something with form.MyResult
    }
    
  • 4

    ShowDialog 方法无法覆盖 . 你可以做的只是创建一个新的方法,它返回ShowDialog结果和另一个值 .

    public ShowDialogResult ShowDialogWrappe(out MyFormResults result) { 
      var dialogRet = ShowDialog();
      result = MyFormResults.Result1;
      return dialogRet;
    }
    

相关问题