我的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;
}我尝试引入一个私有bool,在执行之前设置为true,执行后设置为false。当执行完成时,布尔会被设置,但只有在我单击鼠标按钮或移动鼠标或w/e之后,才会调用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);
}发布于 2017-03-10 16:08:59
在异步场景中,WPF往往不知道何时检查命令,这就是为什么在I命令接口中有"CanExecuteChanged“事件的原因。
在您的命令实现中应该有类似这样的东西:
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void RaiseCanExecuteChanged()
{
CommandManager.InvalidateRequerySuggested();
}使用上面的代码,您现在可以执行以下操作:
public async void Execute(object parameter)
{
mIsExecuting = true;
RaiseCanExecuteChanged ( ); // Not necessary if Execute is not called locally
await ExecuteAsync(parameter);
mIsExecuting = false;
RaiseCanExecuteChanged ( );
}这将告诉WPF您想要刷新命令的CanExecute状态。
https://stackoverflow.com/questions/42712848
复制相似问题