例如,你有一个服务叫做IDialogService
具有以下接口:
public interface IDialogService
{
bool ConfirmAction(string title, string confirmationText);
}
当你为了所提到的,该服务能够证明它需要有对基准的实际对话该视图将显示实际的叠加元素。但不是直接引用我更喜欢通过接口引用它的视图。让我们把它叫做ICanShowDialog
,这将有以下成员:
public interface ICanShowDialog
{
void ShowDialog(object dialogContent);
void HideDialog();
}
这个接口会被你的观点,即拥有该对话框覆盖(例如,你的主窗口)来实现。
现在有趣的部分:暂停对话框显示时的代码执行。首先,我建议你不要使用叠加元素,但如果可能的话使用通常的窗口。那么你不会有这个问题。您可以设计对话窗口的样式,使其看起来就像覆盖元素一样。 无论如何,如果你仍然想使用叠加元素,那么你可以做下面的技巧暂停执行代码:
这里是IDialogService
inteface的ConfirmAction
方法的伪代码:
public bool ConfirmAction(string title, string confirmationText)
{
ConfirmationDialogView dialogView = new ConfirmationDialogView(title, confirmationText);
DialogShower.ShowDialog(dialogView); // DialogShower is of type ICanShowDialog
while (!dialogView.ResultAvailable)
{
DispatcherUtils.DoEvents();
}
DialogShower.HideDialog();
return dialogView.Result;
}
这里的DispatcherUtils.DoEvents()
代码(这是从这里取:http://dedjo.blogspot.com/2007/08/how-to-doevents-in-wpf.html):
public static class DispatcherUtils
{
public static void DoEvents()
{
DispatcherFrame f = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(
DispatcherPriority.Background,
(SendOrPostCallback)delegate(object arg) {
DispatcherFrame fr = arg as DispatcherFrame;
fr.Continue=True;
}, f);
Dispatcher.PushFrame(frame);
}
}
但我必须警告你。使用DoEvents
可能会导致由内部调度程序循环引起的一些微妙的错误。
作为替代,同时会弹出一个对话框,您可以使用回调暂停执行代码:
public interface IDialogService
{
void ConfirmAction(string title, string confirmationText, Action<bool> dialogResultCallback);
}
但它不会那么方便使用。
谢谢帕夫洛,我想避免可能导致微妙的错误的解决方案:) – DaveO 2011-01-20 01:32:14