Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

silverlight - ReactiveUI: Using CanExecute with a ReactiveCommand

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...