首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模拟ShowDialog功能

模拟ShowDialog功能
EN

Stack Overflow用户
提问于 2009-12-01 23:05:01
回答 4查看 3.3K关注 0票数 5

我正在编写一个应用程序(c# + wpf),其中所有模式样式的对话框都作为一个UserControl实现在一个覆盖主Window的半透明网格之上。这意味着只有一个Window,它维护了所有公司应用程序的外观。

要显示MessageBox,语法如下:

代码语言:javascript
复制
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版本相比,它的冗长得可怕:

代码语言:javascript
复制
MessageBox.Show("hello world");
// the rest of the function

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

我是不是遗漏了什么显而易见的东西,或者有没有标准的方法来做到这一点?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2009-12-01 23:17:07

你可能想看看关于CodeProject的this文章和关于MSDN的this文章。第一篇文章将引导您手动创建阻塞模式对话框,第二篇文章将演示如何创建自定义对话框。

票数 5
EN

Stack Overflow用户

发布于 2015-03-30 14:58:15

实现这一点的方法是使用DispatcherFrame对象。

代码语言:javascript
复制
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);
票数 4
EN

Stack Overflow用户

发布于 2009-12-01 23:08:44

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

代码语言:javascript
复制
//some code
yield return new CustomMessageBox("hello world");
//some more code

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1826781

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档