我应该如何使用 Avalonia(ReactiveUI) 控制命令的可执行性?
How should I make a controlling executability of command using Avalonia(ReactiveUI)?
我正在尝试根据本指南实施控制 ReactiveUI 命令的可执行性:guide。
但我得到一个例外:“由于对象的当前状态,操作无效。”
我该如何解决?
我的代码示例:
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;
}
}
在 this.WhenAnyValue
中,您的选择器表达式指向一个字段而不是 属性。改成
this.WhenAnyValue(x => x.Path, x => x.Name, (name, path) => !string.IsNullOrWhiteSpace(name) && !string.IsNullOrWhiteSpace(path));
.
我正在尝试根据本指南实施控制 ReactiveUI 命令的可执行性:guide。
但我得到一个例外:“由于对象的当前状态,操作无效。”
我该如何解决?
我的代码示例:
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;
}
}
在 this.WhenAnyValue
中,您的选择器表达式指向一个字段而不是 属性。改成
this.WhenAnyValue(x => x.Path, x => x.Name, (name, path) => !string.IsNullOrWhiteSpace(name) && !string.IsNullOrWhiteSpace(path));
.