Reputation: 55
I am trying to implement controlling executability of ReactiveUI command according to this guide: guide.
But I am getting an exception: "Operation is not valid due to the current state of the object."
How should I fix that?
My code sample:
public class CreateBookViewModel : ViewModelBase
{
IObservable<bool> canExecuteCreateBookCommand;
private string? name;
private string? path;
public ReactiveCommand<Unit, Unit> ChangePathCommand { get; }
public ReactiveCommand<Unit, EditBookViewModel?> CreateBookCommand { get; }
public string? Name
{
get => name;
set => this.RaiseAndSetIfChanged(ref name, value);
}
public string? Path
{
get => path;
set => this.RaiseAndSetIfChanged(ref path, value);
}
public CreateBookViewModel()
{
canExecuteCreateBookCommand = this.WhenAnyValue(x => x.path, x => x.name, (name, path) =>
!string.IsNullOrWhiteSpace(name) && !string.IsNullOrWhiteSpace(path));
ChangePathCommand = ReactiveCommand.CreateFromTask(RunChangePath);
CreateBookCommand = ReactiveCommand.Create(RunCreateBook, canExecuteCreateBookCommand);
}
private async Task RunChangePath()
{
var dialog = new OpenFolderDialog();
Path = await dialog.ShowAsync(CreateBookWindow.Instance);
}
private EditBookViewModel? RunCreateBook()
{
if(name!= null && path!= null)
{
EditBookViewModel book = new EditBookViewModel(name, path);
return book;
}
return null;
}
}
Upvotes: 2
Views: 331
Reputation: 36
In this.WhenAnyValue
your selector expression is pointing towards a field instead of a property. Change it to
this.WhenAnyValue(x => x.Path, x => x.Name, (name, path) => !string.IsNullOrWhiteSpace(name) && !string.IsNullOrWhiteSpace(path));
.
Upvotes: 1