简体   繁体   English

如何在MDI Form父级上允许ShowDialog MDI子级?

[英]How allows ShowDialog MDI children on MDI Form parent?

In the MDI Parent Forms (With the property this.IsMdiContainer = true ) we don't are allowed to display any children forms with the method ShowDialog() ; 在MDI父表单(具有属性this.IsMdiContainer = true )中,我们不允许使用ShowDialog()方法显示任何子表单; automatically will throw the following exception: 自动将引发以下异常:

A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll 类型“ System.InvalidOperationException”的第一次机会异常发生在System.Windows.Forms.dll中

Additional information: Form that is not a top-level form cannot be displayed as a modal dialog box. 附加信息:不是顶级表单的表单不能显示为模式对话框。 Remove the form from any parent form before calling showDialog. 在调用showDialog之前,从任何父表单中删除该表单。

Did anyone has figured out a workaround this problem? 有谁找到解决此问题的方法?

An easy and clean solution that I implemented on my projects is using a callback function ( Action<T> in C#) that is triggered when the user put the wanted input. 我在项目上实现的一种简单干净的解决方案是使用回调函数(在C#中为Action<T> ),该回调函数在用户放置所需的输入时触发。

Example using ShowDialog: 使用ShowDialog的示例:

private void cmdGetList_Click(object sender, EventArgs e)
{
    string strInput = "";

    frmInputBox frmDialog = new frmInputBox("User input:");

    if (frmDialog.ShowDialog() == DialogResult.OK)
        strInput = frmDialog.prpResult;
    else
        strInput = null;
}

显示对话框 The input box it's outside the MDI Main Form. 输入框在MDI Main Form之外。

Now; 现在; the solution using Show: 使用Show解决方案:

private void cmdGetList_Click(object sender, EventArgs e)
{
    getInput(this, (string strResult) =>
        {
            MessageBox.Show(strResult);
        });
}

private void getInput(Form frmParent, Action<string> callback)
{
    // CUSTOM INPUT BOX
    frmInputBox frmDialog = new frmInputBox("User input:");

    // EVENT TO DISPOSE THE FORM
    frmDialog.FormClosed += (object closeSender, FormClosedEventArgs closeE) =>
    {
        frmDialog.Dispose();
        frmDialog = null;
    };

    frmDialog.MdiParent = frmParent; // Previosuly I set => frmParent.IsMdiContainer = true;

    // frmDialog.ShowDialog(); <== WILL RAISE AN ERROR
    // INSTEAD OF:
    frmDialog.MdiParent = frmParent;

    frmDialog.FormClosing += (object sender, FormClosingEventArgs e) =>
    {
        if (frmDialog.DialogResult == DialogResult.OK)
            callback(frmDialog.prpResult);
        else
            callback(null);
    };

    frmDialog.Show();
}

The input box (Or any form will display inside the MDI parent form): 输入框(或任何表单将显示在MDI父表单内): ShowExample

The trick is to use a callback function (Action on C#) to manage when the user put an input. 诀窍是使用回调函数(对C#进行操作)来管理用户输入内容的时间。

It's more code lines, but it's worthless to display a clean project. 这是更多的代码行,但是显示干净的项目毫无价值。 最后结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM