5

我正在编写一个应用程序(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); 

如您所见,与经典的 .NET 版本相比,不仅执行流程实际上是倒置的,而且还非常冗长:

MessageBox.Show("hello world");
// the rest of the function

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

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

4

4 回答 4

5

您可能想看看CodeProject上的这篇文章和 MSDN上的这篇文章。第一篇文章引导您手动创建阻塞模式对话框,第二篇文章说明如何创建自定义对话框。

于 2009-12-01T15:17:06.803 回答
4

执行此操作的方法是使用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);
于 2015-03-30T06:58:15.110 回答
0

在消息框类中设置另一个消息循环。就像是 :

public DialogResult ShowModal()
{
  this.Show();

  while (!this.isDisposed)
  {
    Application.DoEvents();
  } 

   return dialogResult;
}

如果你在 Reflector 中查看 Windows.Form,你会看到它做了这样的事情。

于 2009-12-01T15:17:52.887 回答
0

你可以把你的函数变成一个返回 的迭代器IEnumerator<CustomMessageBox>,然后这样写:

//some code
yield return new CustomMessageBox("hello world");
//some more code

然后,您将编写一个包装函数,该函数接受枚举器并在处理程序中调用MoveNext(它将执行所有函数,直到下一个yield returnDialogClosed

请注意,包装函数不会是阻塞调用。

于 2009-12-01T15:08:44.363 回答