views:

122

answers:

1

There is a MainWindow,a usercontrol which is located in my MainWindow and a OtherForm which i am going to show from usercontrol. I sent OtherForm as parameter from MainWindow to usercontrol.And in usercontrol i am calling OtherForm.showdialog.When i show it second time ,i am getting "Cannot set Visibility or call Show, ShowDialog, or WindowInteropHelper.EnsureHandle after a Window has closed" problem.

Codes: in MainWindow class

void Example()
{
   usercontrol.Load(new Otherform{ variable= 1 });
}

In Usercontrol class

private Window _form;
public void Load(window form)
{
    _form=form;
}

void ExampleInUSerControl
{
   _form.VerifyAccess();
   _form.Activate();
   _form.ShowActivated = true;
   _form.ShowDialog();
}
+1  A: 

The error message in this case is pretty accurate: once a Window is closed, it's closed for good. Since ShowDialog() always closes the window, you need to create a new instance of the window every time you call ShowDialog().

One fairly simple way to accomplish this in your example is to have the Load event take an argument of type Func<Window>:

In the MainWindow:

private Window MakeWindow()
{
   return new MyWindow();
}

private void Example()
{
   usercontrol.Load(MakeWindow);
}

In the user control:

public void Load(Func<T> makeWindow)
{
   _form = makeWindow();
   ...
}

Note, by the way, that there should be no reason to call Activate or set ShowActivated - ShowDialog will do all that. And I don't know why you'd call VerifyAccess either.

Robert Rossney