附加命令

Attached Command

TL;DR 是否可以将异步可取消命令附加到包含 child

Parent-View-Model

我的问题是,我有一个 ViewModel 对应 View,显示“WizardControl”(如 installation-assistant,您可以在此处单击下一步以进入下一个视图)

Log in 按钮是 Parent-View-Model 的一部分,为此按钮执行的命令必须是来自 Specific Page 的命令的组合(又名 child) 和 MainWindow(又名 parent)。

现在我正在parent的命令中执行child的命令:

ForwardCommand = new DelegateCommand(() =>
{
    CancelEventArgs cea = new CancelEventArgs();
    if (NextCommand != null)
    {
        NextCommand.Execute(null, cea));
        if (!cea.Cancel)
        {
            //Go to next page
        }
        //Else stay on that page because an error occured while the command
    }
},
(nul)=> {
    if (NextCommand != null)
    {
        return true;
    }
    return NextCommand.CanExecute(nul);
});

只要包含的命令不需要异步执行,Login 就是这种情况。因为随后会显示下一页,而无需用户登录即可获取下一页所需的数据。 (登录时第一页会显示加载栏)。对于在执行 Child-Command 时发生错误的情况,我实现了 CancelEventArgs,如您在代码中所见。

提前致谢,
弗洛

PS。 The DelegateCommand 是由 CancellationEventArgs

扩展的 Self-Made 实现

编辑:
我在 Attached Commands 之前的实现是在页面上多了一个 "Log In" 按钮可以点击,并且只有在用户登录后才允许进入下一步,但这样的用户体验很差

为什么一定要是命令?如果您不想将登录功能直接绑定到按钮,请不要提供命令,使用方法:

ForwardCommand = new DelegateCommand( async () =>
{
    if (await _currentlyShownWizardPage.DoYourStuffThatHappensWhenTheUserClicksNext())
        GoToNextPage();
});

另一种方法是反过来构建它:将向导页面的命令绑定到下一个按钮(连同向导页面也提供的按钮内容),并让向导页面的命令将向导前进到下一页(通过向向导页面提供的 IWizard 服务)。