Silverlight Confirm Dialog to Pause Thread

风流意气都作罢 提交于 2019-11-30 14:11:13

I don't think you'll be able to block your code in a message loop the way you can with WinForms' ShowDialog.

However, you can misuse iterators to achieve the same effect:

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;
    ...
}

To use this system, you would write ExecAction(YourMethod());. Note that this would be a semi-blocking call, and that I haven't tested this at all.

C#5's new async features work exactly the same way (in fact, the initial versions of the async compiler code were heavily based on the existing iterator implementation), but with nicer syntactic support.

PL.

You can achieve this quiet easily with RX Framework:

var continued = Observable.FromEvent<RoutedEventArgs>(continueBtn, "Click");

var iter = new Subject<int>();

var ask = iter.Where(i => i == 3).Do(_ => confirm.Show());

iter.Where(i => i != 3 && i < 10)
    .Merge(ask.Zip(continued, (i, _) => i))
    .Do(i => Debug.WriteLine("Do something for iteration {0}", i))
    .Select(i => i + 1)
    .Subscribe(iter);

iter.OnNext(0);

The solution easily scales for any rule determining when to show a dialog. E.g. suppose we want to block the iteration and request user confirmation every 3 iterations. All you have to do is to replace condition i == 3 with i % 3 == 0 (and i != 3 with i % 3 != 0).

Check out this project http://silverlightmsgbox.codeplex.com/. It presents a simple but presentable implementation of several useful message boxes i.e. confirm, error, info, user input, etc. and might be helpful to you. Good luck.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!