如何创建一个自定义按钮,将包含一个变化的图像取决于IsExecuting在AsyncCommand?它需要在不创建UserControl的情况下实现,仅通过继承XAML中的Button(public class CustomButton : Button
)和Style来实现.
public class AsyncCommand : ViewModelBase, ICommand
{
protected readonly Func<Task> _execute;
protected readonly Func<bool>? _canExecute;
private bool _isExecuting;
public bool IsExecuting
{
get => _isExecuting;
set => RisePropertyChanged(ref _isExecuting, value);
}
public AsyncCommand(Func<Task> execute, Func<bool>? canExecute = null)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute;
}
public event EventHandler? CanExecuteChanged;
public bool CanExecute(object? parameter) => !_isExecuting && (_canExecute?.Invoke() ?? true);
public async void Execute(object? parameter)
{
if (CanExecute(parameter))
{
try
{
IsExecuting = true;
await ExecuteAsync(parameter);
}
finally
{
IsExecuting = false;
}
}
OnCanExecuteChanged();
}
protected virtual async Task ExecuteAsync(object? parameter) => await _execute();
protected virtual void OnCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
也许像使用一个event EventHandler? CanExecuteChanged
,这是在ICommand中使用,并由Button响应,而不是RaiseProperty Changed,但我已经没有 idea 了.
我找了很多地方,try 了很多方法来实施它,但没有成功.