当我尝试在默认情况下禁用asny ICommand实现中的命令(即使没有传递CanExecute谓词时),我遇到了奇怪的行为。
public bool CanExecute(object parameter)
{
if (CanExecutePredicate == null)
{
return !mIsExecuting;
}
return !mIsExecuting && CanExecutePredicate(parameter);
}
public async void Execute(object parameter)
{
mIsExecuting = true;
await ExecuteAsync(parameter);
mIsExecuting = false;
}
我尝试引入一个私有的布尔值,我在执行前将其设置为true,在执行后将其设置为false。当执行完成时,该布尔值被设置,但是CanExecute只有在我点击鼠标按钮或移动鼠标等操作后才会被调用。
现在我尝试调用
CanExecute(null);
之后
mIsExecuting = false;
但这也没有帮助。我不知道我缺少了什么。
谢谢你的帮助。
编辑:
为了澄清,我也添加了这个类的构造函数:
public AsyncRelayCommand(Func<object, Task> execute)
: this(execute, null)
{
}
public AsyncRelayCommand(Func<object, Task> asyncExecute,
Predicate<object> canExecutePredicate)
{
AsyncExecute = asyncExecute;
CanExecutePredicate = canExecutePredicate;
}
protected virtual async Task ExecuteAsync(object parameter)
{
await AsyncExecute(parameter);
}
CanExecutePredicate
的竞态条件。 - Alessandro D'Andria