开发者

How do I "Hide()" a Modal WPF Window without it closing?

开发者 https://www.devze.com 2023-01-27 10:25 出处:网络
I have a WPF window that is run on a background thread as a sort of \"notifier window\"... when an event is raised, it displays a message... a user clicks the \"Snooze\" button and I call this.Visibil

I have a WPF window that is run on a background thread as a sort of "notifier window"... when an event is raised, it displays a message... a user clicks the "Snooze" button and I call this.Visibility = Visibility.Collapsed

The very moment 开发者_运维问答that I hide the window (either by calling this.Hide() or setting the Visibility as mentioned above)... the "ShowDialog()" code releases the window and closes it.

This is absolutely a bug in the WPF code (which I've identified via reflector)... but my question remains. Has anyone been able to come up with a work-around for this issue?

I've tried many things and am now reaching out to ya'll smart people :)


You can't hide a modal dialog. That's like asking, "How do I get to 100mph in reverse?" You don't, you drive the car forwards.

Use Show, not ShowDialog. Alternately you can simply re-ShowDialog when it needs to become visible again.


Timothy's Answer is good. I just needed for my scenerio to add the following

window.Closed += new EventHandler(window_Closed);
window.Show();
System.Windows.Threading.Dispatcher.Run(); 

and then in the event...

void window_Closed(object sender, EventArgs e)
{
    System.Windows.Threading.Dispatcher.ExitAllFrames();
}

I needed to do this because it was hanging on the Run after the form was really closed.


  1. In order to show modal window always use ShowDialog().

  2. Use Close() instead of Hide().

  3. Handle the FormClosing event like that:

    private void OnFormClosing(object sender, FormClosingEventArgs e)
    {
        e.Cancel = true;
        this.Visible = false;
    }


OK, and as quickly as that - my boss (old C++ goofy guy that he is) figured out the answer.

Here was the code inside of my background thread (which is set to STA mode):

// Show dialog - keeps the thread open and shows the window! Yay!!!
new BeamUI.Notifier.NotifierWindow().ShowDialog();

And here is the modification, that strangely enough works perfectly :)

// Show... hmm, that shows the window... but how do I keep this thread open?
new BeamUI.Notifier.NotifierWindow().Show();

// ZOMG - a line of code that JUST keeps the thread (and msgpump) going!!!
System.Windows.Threading.Dispatcher.Run();

And that's it.

This kinda thing makes me hate C++ people though, and makes me want to just say "if you just built it right in the first place I wouldn't have to look for a work-around!" (j/k)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号