Luuke
Luuke

Reputation: 141

WPF Create and show a new window inside a method and get its result

I have a Window in WPF and I want to create and show a new instance of it in a method. It is a message box with Yes / No buttons. But it seems like the method need to be "closed" to show my window. In this method are some other things which should be influenced by the control of this window.

private void MyNiceMethod()
{
    MyWindow myWindow = new MyWindow();
    myWindow.Show();

    while (CrazyVariableInfluencedBymyWindow)
    {//Wait}

    //The bool CrazyVariableInfluencedBymyWindow is true usually.
    //And a Button on myWindow set the var to false, so the code in my method
    //continues
}

Is there a way to show a Window, before the method is "closed"?

Upvotes: 0

Views: 387

Answers (2)

thatguy
thatguy

Reputation: 22099

If you want to display a modal dialog, like a confirmation with Yes and No, use ShowDialog.

Opens a window and returns only when the newly opened window is closed.

It returns the bool? value (true, false or null) that you set to the DialogResult property in your MyWindow. The default value is false.

private void MyNiceMethod()
{
    MyWindow myWindow = new MyWindow();
    
    var result = myWindow.ShowDialog();
    CrazyVariableInfluencedBymyWindow = result.GetValueOrDefault();
}

Upvotes: 1

Joey
Joey

Reputation: 354694

Well, yes, the window will not be shown, as the Dispatcher is busy executing your event handler. An endless loop there isn't a good idea. Instead, show the window and set up either a DispatcherTimer to periodically look for your weird variable, or, better yet, just use an event. That's what they're for.

Upvotes: 0

Related Questions