ReactiveUI: Using CanExecute with a ReactiveCommand

泪湿孤枕 提交于 2019-11-30 19:38:44

问题


I'm starting to work with the ReactiveUI framework on a Silverlight project and need some help working with ReactiveCommands.

In my view model, I have something that looks roughly like this (this is just a simplified example):

public class MyViewModel : ReactiveObject
{
  private int MaxRecords = 5;

  public ReactiveCommand AddNewRecord { get; protected set; }

  private ObservableCollection<string> _myCollection = new ObservableCollection<string>();
  public ObservableCollection<string> MyCollection
  {
    get
    {
      return _myCollection;
    }

    set
    {
      _myCollection = value;
      raiseCollectionChanged("MyCollection");
    }
  }

  MyViewModel()
  {
    var canAddRecords = Observable.Return<bool>(MyCollection.Count < MaxRecords);
    AddNewRecord = new ReactiveCommand(canAddRecords);

    AddNewRecord.Subscribe(x => 
    {
       MyCollection.Add("foo");
    }
  }
}

The canAddRecords function is getting evaluated the first time the ReactiveCommand is created, but it's not getting re-evaluated when items are added to MyCollection. Can anyone show me a good example of how to bind the canExecute property of a ReactiveCommand so that it gets automatically re-evaluated in this situation?


回答1:


Actually, there's a better way to do this, change your ObservableCollection to ReactiveCollection (which inherits from ObservableCollection but adds some extra properties):

MyCollection = new ReactiveCollection<string>();

AddNewRecord = new ReactiveCommand(
    MyCollection.CollectionCountChanged.Select(count => count < MaxRecords));

The catch here now is though, you can't overwrite the MyCollection, only repopulate it (i.e. Clear() + Add()). Let me know if that's a dealbreaker, there's a way to get around that too though it's a bit more work.




回答2:


I finally figured this one out. Using ReactiveCommand.Create() worked for my situation.

MyViewModel()
{
  AddNewRecord = ReactiveCommand.Create(x => MyCollection.Count < MaxRecords);

  AddNewRecord.Subscribe(x => 
  {
     MyCollection.Add("foo");
  }
}


来源:https://stackoverflow.com/questions/6754928/reactiveui-using-canexecute-with-a-reactivecommand

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