gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:35:28 24 4
gpt4 key购买 nike

我正在尝试使用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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com