简体   繁体   中英

Create Command with CanExecute based on the Property of an item in an ObservableCollection

I have a ViewModel with a property of type ObservableCollection<T> called Items where T is a class that contains a property called IsSelected of type bool that raises the PropertyChanged event when it's value is changed.

I have a Button that is bound to a Command and I want that Button to be enabled if at least one of the Items' IsSelected property is true and disabled otherwise. I'm trying to do this with ReactiveCommand from ReactiveUI so it would look something like this:

this.SubmitCommand = ReactiveCommand.CreateFromTask(SubmitItems,
     this.WhenAnyValue(x => x.Items).Select(x => x.Any(i => i.IsSelected));

But this doesn't seem to work and I figure that's because the Subscription isn't monitoring the IsSelected property of the Item so when an Item is selected, there's no notification to the Subscription . Anyway, any help would be greatly appreciate it. I think this ReactiveUI stuff is really cool and I'm trying to learn it.

I would use DynamicData.

var canExecute = Items.ToObservableChangeSet()
  .AutoRefreshOnObservable(
    x => x.WhenAnyValue(item => item.IsSelected))
  .ToCollection()
  .Select(x => x.Any(item => item.IsSelected));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM