ReactiveCommand CanExecute 对集合中的变化做出反应 [英] ReactiveCommand CanExecute reacting to changes in a collection
问题描述
我有一个充满项目的 ReactiveCollection(也是 ReactiveObjects).
I have a ReactiveCollection filled with Items (that are ReactiveObjects as well).
我想创建一个只有当集合中的任何项的某些属性设置为 true 时才应启用的 ReactiveCommand,例如:
I want to create a ReactiveCommand that should be enabled only when any of the items in the collection has some property set to true, something like:
MyCommand = ReactiveCommand.Create( watch items in collection to see if item.MyProp == true )
因此,只要其中一项属性设置为 true,就应该启用该命令.
So anytime there is one of the items with the property set to true, the command should be enabled.
谢谢,保罗.生成的代码是这样的:
Thanks, Paul. The resulting code is this:
public MainViewModel()
{
Items = new ReactiveList<ItemViewModel>
{
new ItemViewModel("Engine"),
new ItemViewModel("Turbine"),
new ItemViewModel("Landing gear"),
new ItemViewModel("Wings"),
};
Items.ChangeTrackingEnabled = true;
var shouldBeEnabled = Items.CreateDerivedCollection(x => x.IsAdded);
var shouldRecheck = Observable.Merge(
// When items are added / removed / whatever
shouldBeEnabled.Changed.Select(_ => Unit.Default),
// When any of the bools in the coll change
shouldBeEnabled.ItemChanged.Select(_ => Unit.Default));
// Kick off a check on startup
shouldRecheck = shouldRecheck.StartWith(Unit.Default);
ClearCommand = ReactiveCommand.Create(shouldRecheck.Select(_ => shouldBeEnabled.Any(x => x)));
}
编辑 2:我发现了一个陷阱!如果你修改这一行:
EDIT 2: I've discovered a trap! If you modify this line:
new ItemViewModel("Engine");
并像这样设置 IsAdded = true
and set the IsAdded = true like this
new ItemViewModel("Engine") { IsAdded = true };
...当您运行时,应用程序启动时按钮被禁用,应该启用.似乎在发生某些更改后不会对表达式进行评估.我该如何解决?
… when you run the button is disabled when the application starts and it should be enabled. It seems like the expression doesn't evaluate after some change occurs. How can I solve it?
编辑 3: 解决了!正如@paul-betts 所说,可以通过添加以下行来解决:
EDIT 3: Solved! As @paul-betts says, it can be solved adding this line:
// Kick off a check on startup
shouldRecheck = shouldRecheck.StartWith(Unit.Default);
上面的代码示例也更新了(在他的回答中也是如此).
The code sample is also update above (and in his answer, too).
推荐答案
这个怎么样
mySourceCollection.ChangeTrackingEnabled = true;
shouldBeEnabled = mySourceCollection.CreateDerivedCollection(x => x.MyProp);
var shouldRecheck = Observable.Merge(
// When items are added / removed / whatever
shouldBeEnabled.Changed.Select(_ => Unit.Default),
// When any of the bools in the coll change
shouldBeEnabled.ItemChanged.Select(_ => Unit.Default));
// Kick off a check on startup
shouldRecheck = shouldRecheck.StartWith(Unit.Default);
myCmd = ReactiveCommand.Create(shouldRecheck.Select(_ => shouldBeEnabled.All(x => x));
这篇关于ReactiveCommand CanExecute 对集合中的变化做出反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!