0

有一个 MainViewModel 有一个 ActiveLayoutItem 属性,该属性只有在 Add() 命令之后才被初始化,即 MainViewModel 构造函数初始化时,该属性将为 null。MainViewModel 有一个 ReactiveCommandCheck 命令,该命令有两个可以执行的条件:

  1. ActiveLayoutItem 必须是非 null 并且是 PropertiesViewModel(ActiveLayoutItem 是 PropertiesViewModel)!=空;
  2. (ActiveLayoutItem 作为 PropertiesViewModel) .ReactiveCommand1.CanExecute == true;

如何实现这个命令?

 public class MainViewModel : ViewModelBase
{
    public ReactiveCommand<Unit, Unit> ReactiveCommandCheck { get; set; }
    public void RC1Ex()
    {
        this.Tools.Clear();
    }
    public ViewModelBase ActiveLayoutItem
    {
        get
        {
            return _activeLayoutItem;
        }
        set => this.RaiseAndSetIfChanged(ref _activeLayoutItem, value);
    }
    public MainViewModel()
    {
        ReactiveCommandCheck = ReactiveCommand.Create(RC1Ex, ***??? ***);
    }

    public void Add()
    {
        var vm = new PropertiesViewModel();
        ActiveLayoutItem = vm;
    }
}

public class PropertiesViewModel : ViewModelBase
{
    public ReactiveCommand<Unit, Unit> ReactiveCommand1 { get; }
    public void RC1Ex()
    {
        Title = "";
    }
    public PropertiesViewModel()
    {
        Title = "Documents Properties";

        var canEx = this.WhenAnyValue(
            x => x.Title,
            x => !string.IsNullOrWhiteSpace(x));

        ReactiveCommand1 = ReactiveCommand.Create(RC1Ex, canEx);
    }
}
4

1 回答 1

0

猜测第一个条件可以这样表示:

var layoutItemIsValid =
    this.WhenAnyValue(x => x.ActiveLayoutItem)
        .Select(item => item != null && item is PropertiesViewModel);

第二个条件可能看起来有点像:

var canExecuteChanged =
    this.WhenAnyValue(x => x.ActiveLayoutItem)
        .OfType<PropertiesViewModel>() // This filters out irrelevant types.
        .SelectMany(props => props.ReactiveCommand1.CanExecute);

我们需要结合这两个条件:

var canDoStuff = 
    layoutItemIsValid.CombineLatest(
        canExecuteChanged,
        (valid, canExecute) => valid && canExecute);

这需要测试,但我希望这至少有一点帮助。

于 2020-12-04T19:00:50.117 回答