0
votes

I have a Xamarin Forms CollectionView of items that is set to SelectionMode="Single" and binds SelectedItem to a ViewModel property.

The ViewModel property looks like this:

private TaskItem _selectedTask;

    public TaskItem SelectedTask
    {
        get => _selectedTask;
        set => this.RaiseAndSetIfChanged(ref _selectedTask, value);
    }

I also have a button bound to a ReactiveCommand and I want to add a CanExecute parameter.

When the app first starts up, the ViewModel's SelectedTask property is null because no item in the CollectionView has been selected. So I want my CanExecute to return true only if an item is selected. That would mean that SelectedTask would no longer be null. But I can't figure out how to test if the entire object is null rather than a property of the object. In other words, I want to do something like this:

IObservable<bool> DeleteTaskCanExecute()
{            
    return this.WhenAnyValue(x => x.SelectedTask,
        selectedTask => selectedTask != null                    
      );
}

But I cannot because it then has an error that the WhenAnyValue call is ambiguous between two signatures since it is expecting me to make an expression based upon a TaskItem property rather than the TaskItem object that SelectedTask represents.

I think WhenAnyValue is not the appropriate function to use because of that, but I have not been able to find what I would use instead.

How do I make a CanExecute function that will work with the ReactiveUI command and only return true when something in the CollectionView has been selected?

1
this.WhenAnyValue(x => x.SelectedTask).WhereNotNull()xleon
I actually had already tried using WhereNotNull(), but that returns an IObservable<TaskItem> whereas the CanExecute needs an IObservable<bool>VinceL

1 Answers

1
votes
IObservable<bool> DeleteTaskCanExecute()
{            
    return this
        .WhenAnyValue(x => x.SelectedTask)
        .Select(x => x != null);
}