✅ Help needed: Buttons update enabled state after two clicks.
Hello,
I need help to find out why it takes two clicks before the buttons change the enabled state.
Please see the attached video and also my code below:
I need help to find out why it takes two clicks before the buttons change the enabled state.
Please see the attached video and also my code below:
<StackLayout>
<Button Text="Start the service" Command="{Binding StartTheServiceCommand}" />
</StackLayout>
<StackLayout>
<Button Text="Stop the service" Command="{Binding StopTheServiceCommand}" />
</StackLayout> <StackLayout>
<Button Text="Start the service" Command="{Binding StartTheServiceCommand}" />
</StackLayout>
<StackLayout>
<Button Text="Stop the service" Command="{Binding StopTheServiceCommand}" />
</StackLayout>public MainPageViewModel(ILogger<MainPageViewModel> logger, WorkerService workerService)
{
_logger = logger;
_workerService = workerService;
StartTheServiceCommand = new Command(
execute: () =>
{
_logger.LogInformation("Starting the service at: {time}", DateTimeOffset.Now);
Task.Run(async () => await _workerService.StartAsync(new()));
RefreshCanExecutes();
},
canExecute: () => !_workerService.IsRunning);
StopTheServiceCommand = new Command(
execute: () =>
{
_logger.LogInformation("Stopping the service at: {time}", DateTimeOffset.Now);
Task.Run(async () => await _workerService.StopAsync(new()));
RefreshCanExecutes();
},
canExecute: () => _workerService.IsRunning);
}
public ICommand StartTheServiceCommand { get; }
public ICommand StopTheServiceCommand { get; }
private void RefreshCanExecutes()
{
(StartTheServiceCommand as Command)!.ChangeCanExecute();
(StopTheServiceCommand as Command)!.ChangeCanExecute();
}public MainPageViewModel(ILogger<MainPageViewModel> logger, WorkerService workerService)
{
_logger = logger;
_workerService = workerService;
StartTheServiceCommand = new Command(
execute: () =>
{
_logger.LogInformation("Starting the service at: {time}", DateTimeOffset.Now);
Task.Run(async () => await _workerService.StartAsync(new()));
RefreshCanExecutes();
},
canExecute: () => !_workerService.IsRunning);
StopTheServiceCommand = new Command(
execute: () =>
{
_logger.LogInformation("Stopping the service at: {time}", DateTimeOffset.Now);
Task.Run(async () => await _workerService.StopAsync(new()));
RefreshCanExecutes();
},
canExecute: () => _workerService.IsRunning);
}
public ICommand StartTheServiceCommand { get; }
public ICommand StopTheServiceCommand { get; }
private void RefreshCanExecutes()
{
(StartTheServiceCommand as Command)!.ChangeCanExecute();
(StopTheServiceCommand as Command)!.ChangeCanExecute();
}