views:

30

answers:

2

Some context here...I have a System.Windows.Window that is used to display a modal message box. I created a Show() method that initializes the content of the window, and then calls ShowDialog(). The user clicks a button on this window, some information about the clicked button is set in the Tag property, and then the window is closed via Close().

As expected, I get a ShowDialog Exception when attempting to call ShowDialog() on the Window once is has been closed. Is there some way to reuse that same Window instance so that I don't have to new up an instance every time I need a message box?

For example...

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!

+1  A: 

Hello

Use .Hide() instead of .Close(). That removes it without destroying it. Then you can call Show() again when needed.

 MainWindow test = new MainWindow();
  test.Show();
  test.Hide();
  test.Show();
Jay Allard
Thanks! Very simple solution that works for the problem I needed to solve.
geoffmazeroff
A: 

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

For example:

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;
  }
}
Jack
Instead of using Visible you could use the Hide() and Show() methods with this approach as well as suggested in Jay's answer
Jack
This is solution probably the most complete method of solving the problem using the events pertaining to the window. Unfortunately, my team lead said for the message box to be compatible with our IoC, therefore static methods tend to be problematic. If the IoC weren't in the picture, I would use this solution. Thanks!
geoffmazeroff
If it is just the static method (and not the event handlers) that is the problem the show method doesn't have to be static. I only made it static because the way I wrote it allowed it to be static. Force of habit I guess.
Jack