tags:

views:

634

answers:

3

I have a Window instance which I show by calling wInstance.ShowDialog() from a button click and I close the window by pressing Alt+F4. The issue now is that I cant call wInstance.ShowDialog() again. How can I re-use the same window instance again.

Exception : Cannot set Visibility or call Show or ShowDialog after window has closed.

+1  A: 

What exactly is it that makes it so important to use the same window? If you are using MVVM, you could just reuse the viewmodel for a new window.

Botz3000
But I want to eliminate the cost of a new Window instance creation. So checking whether there is a re-usability scope and use ShowDialog() again on the instance.
Jobi Joy
Is your window that expensive to create?
Botz3000
Martin Doms's answer is correct, but I'm very curious about this question myself. Is it possible you are overestimating the overhead of creating this view, especially if you are using MVVM and keeping the VM around?
Anderson Imes
+6  A: 

You need to override the wInstance OnClosing method to set the window visibility to hidden and cancel the close event.

 protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
    {
        this.Visibility = Visibility.Hidden;
        e.Cancel = true;
    }
Martin Doms
Thanks Martin, this is the answer to a question that I was asking myself the other day.
Dennis Roche
I have the same problem here and although this stopped the exception when I try to use the window again, it is preventing the ShowDialog() from returning true when I would expect. Do you have any suggestions about this?
EasyTimer
The return for ShowDialog() indicates how the dialog was disposed of. If this information is important to you then you will need to actually dispose of the window when it is closed, so you shouldn't cancel the close event, and instead instantiate a new Window when you want to reopen it. If state information of the window is important consider the memento pattern.
Martin Doms
A: 

I'm reusing a window as a Dialog that uses a treeview and the client wants the tree branches to remain open for a more selections.

The override worked for re-use, and the branches stay expanded.

I'm not using a view model to keep it simple as it is a read only selection dialog. But since I can't seem to clear the selection yet, I may have to switch to a view model.

Dave