Is it possible to re-show and close the dialog box?

In some context here ... I have a System.Windows.Window that is used to display a modal message box. I created the Show () method, which initializes the contents of the window, and then calls ShowDialog (). The user clicks a button in this window, some information about the pressed button is set in the tag property, and then the window is closed using Close ().

As expected, I get a ShowDialog exception when I try to call ShowDialog () on the window once when it was closed. Is there a way to reuse the same instance of Window so that I don't have to update the instance every time I need a message box?

For instance...

MessageBoxWindow mbw = new MessageBoxWindow(); result = mbw.Show("caption", "message 1"); mbw.Show("caption", "message 2"); // The above throws an exception, so I have to do this... mbw = new MessageBoxWindow(); result = mbw.Show("caption", "message 2"); 

Any help would be greatly appreciated!

+4
source share
2 answers

Use .Hide () instead of .Close (). This removes it without destroying it. You can then call Show () again when necessary.

  MainWindow test = new MainWindow(); test.Show(); test.Hide(); test.Show(); 
+2
source

You can add a FormClosing event that cancels the close form and instead sets the Form.Visible parameter to false. Then you will also need the Show method, which checks if this form is zero, so you need to know if you need to create a new form or just show the one you already have.

For instance:

 private void FormMessageBox_FormClosing(object sender, FormClosingEventArgs e) { //This stops the form from being disposed e.Cancel = true; this.Visible = false; } public static void Show(FormMessageBox formMessageBox, string message) { //if formMessageBox is null we need to create a new one otherwise reuse. if (formMessageBox == null) { formMessageBox = new FormMessageBox(message); formMessageBox.ShowDialog(); } else { formMessageBox.lblMessage.Text = message; formMessageBox.Visible = true; } } 
0
source

Source: https://habr.com/ru/post/1316663/


All Articles