0

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?

2
  • this.WhenAnyValue(x => x.SelectedTask).WhereNotNull() Commented Jun 3, 2021 at 8:37
  • I actually had already tried using WhereNotNull(), but that returns an IObservable<TaskItem> whereas the CanExecute needs an IObservable<bool> Commented Jun 3, 2021 at 18:54

1 Answer 1

1
IObservable<bool> DeleteTaskCanExecute()
{            
    return this
        .WhenAnyValue(x => x.SelectedTask)
        .Select(x => x != null);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.