How to detect that the window has exhausted the call to "ShowDialog"

In WPF, you call ShowDialog on the window exactly once. After that it is done for.

I seem awkward, but these are the rules. If you call ShowDialog again, you get this exception:

Cannot set visibility or call Show, ShowDialog or WindowInteropHelper.EnsureHandle after closing a window

I want to know: how can I take a Window (or UserControl really) and check if it has a ShowDialog (so I know that new before another calls ShowDialog again).

Something like that:

 public void ShowListOfClients() { // | This is the method I want to write // V RefreshViewIfNeeded(_myWindowOrUserControlThatShowsAList); FillWindowWithBusinessData(_myWindowOrUserControlThatShowsAList); _myWindowOrUserControlThatShowsAList.ShowDialog(); } 

NOTE. . Obviously, in the above example, it would be easier to just create a new WindowOrUserControlThatShowsAList every time I introduce a method. But please consider what the given example is.

+7
c # wpf
source share
3 answers

This is not exclusive to ShowDialog (), Show () does this too. And no, there is no IsDisposed property to check. IsLoaded is only half the solution, it will be false for the first call.

The first approach is to simply make a dialog that can be re-displayed:

  public bool CloseAllowed { get; set; } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if (!CloseAllowed) { this.Visibility = System.Windows.Visibility.Hidden; e.Cancel = true; } } 

The following is to explicitly track the health of an object link:

  private Window1 win = new Window1(); // say private void button1_Click(object sender, RoutedEventArgs e) { if (win == null) { win = new Window1(); win.Closing += delegate { win = null; }; } win.ShowDialog(); } 
+9
source share

Well, the dirty way to do this is to catch an exception.

A clean way to do this is to show the window with ShowDialog and destroy (lose the link, etc.) the window when the function returns. Presentation should not be closely related to models (are you using MVVM correctly?), Therefore, creating new visual objects for each type of client should not be a problem.

+3
source share

A simple way to deal with this problem without ruining the close event:

 public partial class MainWindow { private SomeCustomWindow _someCustomWindow; public MainWindow() { InitializeComponent(); } private void OnOpenCustomWindowButtonClick(object sender, RoutedEventArgs e) { if (_someCustomWindow != null) _someCustomWindow.Close(); _someCustomWindow = new SomeCustomWindow(); _someCustomWindow.ShowDialog(); } private void OnWindowClosing(object sender, CancelEventArgs e) { if (_someCustomWindow!= null) _someCustomWindow.Close(); } } 
0
source share

All Articles