silverlight - Silverlight确认对话框以暂停线程

标签 silverlight dialog confirm childwindow

我正在尝试使用Silverlight的ChildWindow对象进行确认对话框。

理想情况下,我希望它像MessageBox.Show()一样工作,在该应用程序中,整个应用程序将暂停,直到收到用户的输入为止。

例如:

for (int i = 0; i < 5; i++)
{
    if (i==3 && MessageBox.Show("Exit early?",
        "Iterator", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
    {
        break;
    }
}

如果用户点击确定,将在3处停止迭代...

但是,如果我要按部就类地做一些事情:
ChildWindow confirm = new ChildWindow();
confirm.Title = "Iterator";
confirm.HasCloseButton = false;
Grid container = new Grid();

Button closeBtn = new Button();
closeBtn.Content = "Exit early";
closeBtn.Click += delegate { confirm.DialogResult = true; confirm.Close(); };
container.Children.Add(closeBtn);

Button continueBtn = new Button();
continueBtn.Content = "Continue!";
continueBtn.Click += delegate { confirm.DialogResult = false; confirm.Close(); };
container.Children.Add(continueBtn);

confirm.Content = container;

for(int i=0;i<5;i++) {
  if (i==3) {
    confirm.Show();
    if (confirm.DialogResult.HasResult && (bool)confirm.DialogResult) {
      break;
    }
  }
}

这显然不起作用,因为线程没有停止... confirm.DialogResult.HasResult将为false,并且循环将持续到3以上。

我只是想知道,我该如何正确处理。 Silverlight是单线程的,所以我不能只让线程进入休眠状态,然后在准备就绪时将其唤醒,所以我只是想知道人们是否还有其他建议?

我已经考虑过颠倒逻辑-即,将我想发生的 Action 传递给“是/否”事件,但是在我的特定情况下,这不太可行。

提前致谢!

最佳答案

我认为您无法像使用WinForms的ShowDialog一样在消息循环中阻止代码。

但是,您可以滥用迭代器来达到相同的效果:

interface IAction { void Execute(Action callback); }

public static void ExecAction(IEnumerator<IAction> enumerator) {
    if (enumerator.MoveNext())
        enumerator.Current.Execute(() => ExecAction(enumerator));
}

class DialogAction : ChildWindow, IAction {
    void IAction.Execute(Action callback) {
       //Show the window, then call callback when it's closed
    }
}

IEnumerator<IAction> YourMethod() { 
    ...
    var confirm = new DialogAction();
    yield return confirm;
    if (confirm.DialogResult.HasResult && (bool)confirm.DialogResult)
        yield break;
    ...
}

要使用此系统,您需要编写ExecAction(YourMethod());。请注意,这将是一个半阻塞调用,并且我根本没有测试过。

C#5的新async功能的工作方式完全相同(实际上,async编译器代码的初始版本很大程度上基于现有的迭代器实现),但是具有更好的语法支持。

关于silverlight - Silverlight确认对话框以暂停线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2113501/

相关文章:

javascript 确认阻止 Chrome 中的屏幕更新

c# - 如何在 XAML 中换行或换行

c# - 在服务器端运行连续的自定义应用程序逻辑。入口点?

javascript - 如何将按钮传递到 Jquery 函数中?

exception - JavaFX对话框异常

ruby-on-rails-3 - 在 link_to :confirm 中使用变量

javascript - JQuery 确认链接对话框仅适用于列表中的第一个

wpf - 在 Blend 设计时使用 Moq

wpf - 为什么我们需要在IValue Converter中使用ConvertBack

C++ 异常处理程序问题