Reputation: 655
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 the second time, I am getting "Cannot set Visibility or call Show, ShowDialog, or WindowInteropHelper.EnsureHandle after a Window has closed" problem.
Code
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();
}
Upvotes: 0
Views: 2721
Reputation: 96820
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.
Upvotes: 2