从另一个命令执行一个命令

问题描述 投票:0回答:2

我有一个“hello world”表单(Xamarin 表单),其中包含一些字段和一个提交按钮。有一个可观察对象 (CanSave) 控制 SaveChangesCommand 何时可以执行。如果在 CanSave 为 false 时按下保存按钮,我想向用户显示一条消息。

使用下面的代码,如果我

  1. 输入错误数据
  2. 单击“保存”(显示错误消息)
  3. 然后修正数据。

CanSave 变为 true 并执行 SaveChangesCommand - 在再次点击按钮之前。就好像先前阻止的按钮按下已排队,直到 canExecute 变为 true。

我错过了什么?

谢谢:-)

 public PersonalProfileModel()
    {
        this.SaveChangesCommand = ReactiveCommand.CreateAsyncTask(this.CanSave(),  message => this.doAllThings(message as string));
        this.ButtonClickedCommand = ReactiveCommand.Create(Observable.Return(true));
        this.ButtonClickedCommand.InvokeCommand(this.SaveChangesCommand);
        // ButtonClickedCommand.Subscribe(x => this.SaveChangesCommand.Execute("hello")); // tried this too
    }

    public ReactiveCommand<object> ButtonClickedCommand { get; set; }
    public ReactiveCommand<string> SaveChangesCommand;

    public IObservable<bool> CanSave()
    {
        var fieldsValid = this.WhenAnyValue(
            x => x.Name,
            x => x.Country,
            (f1, f2) =>
                f1 == "a"
                && f2 == "b");
        return fieldsValid;
    }

    public Task<string> doAllThings(string message)
    {
        var result = Task.Run(() =>{return "hello " + message;});
        return result;
    }
c# reactiveui
2个回答
1
投票

这个怎么样:

this.SaveChangesCommand = ReactiveCommand.CreateAsyncTask(
    this.CanSave(),  
    message => this.doAllThings(message as string));

this.ButtonClickedCommand = ReactiveCommand.CreateAsyncObservable(
    SaveChangesCommand.CanExecuteObservable.StartWith(true),
    x => SaveChangesCommand.ExecuteAsync(x));

现在我们用 SaveChangesCommand 来明确描述 ButtonClicked 的命令之间的关系 - “当 SaveChanges 可以执行时,ButtonClicked 命令被启用”


1
投票

事实证明这是对 ReactiveCommands 和 canExecute 行为的误解。 请参阅 ReactiveCommand 不尊重 canExecute

© www.soinside.com 2019 - 2024. All rights reserved.