Xamarin.Forms 按钮在触摸后变为禁用状态

Xamarin.Forms buttons become disabled after touched

我使用了Xamarin.Forms和MvvmCross,但是我在应用程序中遇到了问题。 按钮有时会在触摸和 运行 命令后失效。

我将 IsEnabled="True" 添加到按钮,但没有任何改变

<Button 
    WidthRequest="36" 
    HeightRequest="36" 
    CornerRadius="18" 
    BorderWidth="2" 
    FontSize="18" 
    Text="{Binding OptionText}" 
    Command="{Binding OptionSelectedCommand}" 
    CommandParameter="{Binding .}" 
    IsEnabled="True" 
    VerticalOptions="Center" 
    HorizontalOptions="Center"/>

我希望此按钮始终处于启用状态。

我的命令代码是:

new MvxAsyncCommand(async () => 
{ 
    if (option.IsSelected) 
    { 
        option.IsSelected = false; 
    } 
    else 
    { 
        option.OptionGroup.Options.ForEach(c => c.IsSelected = false);
        option.IsSelected = true; 
    } 

    return Task.CompletedTask; 
})

最后我找到了解决这个问题的方法。 问题与 MvxAsyncCommand 有关,通过使用 Command 而不是 MvxAsyncCommand 来解决。

我认为 MvvmCross MvxAsyncCommand 有一个关于 运行 异步方法的错误

Mehmet 是正确的,这个问题的根源在于 MvxAsyncCommand。我发现我的 MvxAsyncCommand 的 CanExecute() 方法总是 returned false。当 CanExecute() return 为 false 时,Xamarin Forms 按钮将被禁用,这是预期的行为。但是为什么 CanExecute() 总是 return false?我深入研究了源代码,发现如果 MvxAsyncCommand 的 CanExecute() 方法认为任务是 运行,它将 return 为 false。如果您在 MvxAsyncCommand 的构造函数中将 allowConcurrentExecutions 设置为 true,它将绕过该检查并且按钮将再次启用。

这需要在 MvxAsyncCommand 中修复,但设置 allowConcurrentExecution = true 是一种临时解决方法。

MvxAsyncCommand on Github:

public bool CanExecute(object parameter)
{
    if (!_allowConcurrentExecutions && IsRunning)
        return false;
    else
        return CanExecuteImpl(parameter);
}