ReactiveUI:将CanExecute与ReactiveCommand一起使用 [英] ReactiveUI: Using CanExecute with a ReactiveCommand
问题描述
我开始在Silverlight项目上使用ReactiveUI框架,并且需要一些使用ReactiveCommands的帮助.
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");
}
}
}
第一次创建ReactiveCommand
时将对canAddRecords
函数进行评估,但是将项目添加到MyCollection
中时不会对其进行重新评估.谁能给我展示一个很好的示例,说明如何绑定ReactiveCommand
的canExecute
属性,以便在这种情况下自动重新评估它?
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?
推荐答案
实际上,有一种更好的方法,将ObservableCollection更改为ReactiveCollection(继承自ObservableCollection,但添加了一些额外的属性):
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));
虽然现在的问题是,您不能覆盖 MyCollection,只能重新填充它(即Clear()+ Add()).让我知道这是否是一个破坏交易的方法,尽管还有很多工作要做,但是也有一种解决方法.
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.
这篇关于ReactiveUI:将CanExecute与ReactiveCommand一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!