0

我正在从我的父表单中调用一个表单的 ShowDialog,并且我正在填充子表单中的一些数据,我想通过它在我的父表单中调用一个方法。

我父表单中的方法更新我表单中的控件值。

这导致我出现线程中止异常

说喜欢

ChildForm Cform=new ChildForm();
Cform.ShowDialog();

在 ChildForm 中

ParentForm PForm=new Parentform();
PForm.Somemethod();//method in my parentForm

在某种方法中,我通过调用来更新表单中控件的值

我正在调用每个控件,但仍然收到ThreadAbort 异常

注意:我正在使用 Compact Framework

//My parent Form Method
       public void ProcessResponse()
        {

            Result Objresult = new Result();

            Objresult.ShowDialog();

        }

    //My child Form
      public void SendBackResponse()
      {
      //Some Processing
       ParentForm PForm=new Parentform();
        PForm.Somemethod();
      }

And In ParentForm I am having 

    public void Somemethod()
    {
        if(InvokeRequired)
        {
         //I am invoking Through the delegate
        }
    }

提前致谢

4

1 回答 1

1

这里有几个问题。

首先,您的“父”表单不是名为 ShowDialog 的表单。您实际上是在 Child 中创建了一个全新的 Form 实例,因此它与创建 Child 的 Parent 不同。

其次,ShowDialog 为正在显示的 Dialog 创建一个单独的消息泵。在对话框关闭并且主消息泵再次开始运行之前,不会处理发送到父级的任何 Windows 消息。这意味着在对话框关闭之前,父级上的任何 UI 更新都不会发生。

第三,你所做的只是糟糕的设计。如果您需要父级以某种 UI 方式对子级做出反应,则在子级中公开一个属性,在子级关闭时读取它并处理更新:

class Child : Form
{
    ....
    public string NewInfo { get; set; }
}

....

// code in the Parent
var child = new ChildForm();
if(child.ShowDialog() == DialogResult.OK)
{
   this.UseChildData(child.NewInfo);
}

如果您不更新父 UI,而是运行某种形式的业务逻辑,那么您就违反了关注点分离。将该业务逻辑放入 Presenter/Controller/ViewModel/Service/Model/whatever 并将其传递给子级。

class Service
{
    public void DoSomething() 
    {
        // business logic here 
    } 
}

class Child : Form
{
    Service m_service;

    public Child(Service service)
    {
        m_service = service;
    }

    void Foo()
    {
        // call the business logic
        m_service.DoSomething();
    }
}

....

// code in the Parent
var svc = new Service();
....
var child = new ChildForm(svc);
child.ShowDialog();
于 2013-09-04T17:40:17.173 回答