user995387
user995387

Reputation: 385

How to use WPF window as a messagebox?

I have created a small window with some style. Now i want to use it as exactly like a MessageBox. How can i achieve it?

Edit: I am new to WPF. I tried calling it in the main window like this.

Window1 messageBox = new Window1();
messageBox.Show();
messageBox.Activate();

The problem is the newly generated window disappears just behind main window without letting me to click on the action button in it.

Upvotes: 5

Views: 1643

Answers (1)

Haris Hasan
Haris Hasan

Reputation: 30097

Use ShowDialog instead of Show method to popup the messagebox window. In this way user will hve to first close the popup or message box window before moving back to main window

 MessageWindow message= new MessageWindow();
 message.ShowDialog();

Edit

You obviously would like to have result back in the main windows right? you can do it in several ways. One simplest way could be to expose a public method in MainWindow

public GetResult(bool result)
{
   //your logic
} 

Create a constructor of MessageWindow that take MainWindow in parameter

 private MainWindow window;
 public MessageWindow(MainWindow mainWindow)
        {
            InitializeComponent();
            window = mainWindow;
        }
   //now handle the click event of yes and no button
  private void YesButton_Click(object sender, RoutedEventArgs e)
        { 
            //close this window
            this.Close();
            //pass true in case of yes
            window.GetResult(true);
        }

        private void NoButton_Click_1(object sender, RoutedEventArgs e)
        {
            //close this window
            this.Close();
            //pass false in case of no
            window.GetResult(false);
        }
 //in that case you will show the popup window like this
 MessageWindow message= new MessageWindow(this);
 message.ShowDialog();

Upvotes: 7

Related Questions