模拟ShowDialog功能

Guy*_*Guy 5 c# wpf events dialog messagebox

我正在编写一个应用程序(c#+ wpf),其中所有模态样式对话框都实现为UserControl覆盖main的半透明网格Window.这意味着只有一个Window,它保持了所有公司应用程序的外观和感觉.

要显示a MessageBox,语法如下:

CustomMessageBox b = new CustomMessageBox("hello world");
c.DialogClosed += ()=>
{
   // the rest of the function
}
// this raises an event listened for by the main window view model,
// displaying the message box and greying out the rest of the program.
base.ShowMessageBox(b); 
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,不仅执行流程实际上已经反转,而且与经典的.NET版本相比,它的冗长程度如此:

MessageBox.Show("hello world");
// the rest of the function
Run Code Online (Sandbox Code Playgroud)

我真正想要的是一种不会返回的方法,base.ShowMessageBox直到它引发了对话框关闭事件,但是我无法看到如何在不挂起GUI线程的情况下等待这一点,从而阻止用户点击OK.我知道我可以将一个委托函数作为函数的参数来ShowMessageBox阻止执行的反转,但仍会导致一些疯狂的语法/缩进.

我错过了一些明显的东西,还是有标准的方法来做到这一点?

Chr*_*uts 5

你可能想看看这个文章在CodeProject上和这个文章在MSDN上.第一篇文章将指导您手动创建阻塞模式对话框,第二篇文章介绍如何创建自定义对话框.


Cam*_*and 5

完成此操作的方法是使用DispatcherFrame对象。

var frame = new DispatcherFrame();
CustomMessageBox b = new CustomMessageBox("hello world");
c.DialogClosed += ()=>
{
    frame.Continue = false; // stops the frame
}
// this raises an event listened for by the main window view model,
// displaying the message box and greying out the rest of the program.
base.ShowMessageBox(b);

// This will "block" execution of the current dispatcher frame
// and run our frame until the dialog is closed.
Dispatcher.PushFrame(frame);
Run Code Online (Sandbox Code Playgroud)