10

I have bound button command to one RelayCommand from MVVM Toolkit, which executes some function, with following:

[RelayCommand]
private async void SomeMethod() {}

I want to prevent multiple clicks on the button hence, preventing multiple method calls via CanExecute parameter of RelayCommand, but I can't figure that one out.

I know that RelayCommand first checks with CanExecute if it is possible to execute the command, but I do not understand how to go about implementing it.

I have searched numerous questions on the topic but could get nowhere near to solution.

Edit: Also there is no SomeMethod.isRunning property.

2 Answers 2

14

To implement CanExecute, You can try the following example:

[RelayCommand(CanExecute = nameof(IsSomeMethodExcutable))]
private async void SomeMethod(){}

private bool IsSomeMethodExcutable() { return _isBusy;}
Sign up to request clarification or add additional context in comments.

1 Comment

I believe that this should be the accepted answer. The RelayCommand has the correct signature private async void and adding the CanExecute parameter specifies the method to call when the CanExecute state changes. The only other thing needed is to call SomeMethodCommand.NotifyCanExecuteChanged(); in a method that changes the state of _isBusy
3

To specifically answer your need:

I want to prevent multiple clicks on the button

you can use the AllowConcurrentExecution parameter of the RelayCommand attribute:

[RelayCommand(AllowConcurrentExecutions = false)]
private async Task SomeMethod()
{
    await Task.Delay(1000); // Perform real stuff here
}

2 Comments

The default value of AllowConcurrentExecution is false.
That is correct, mentioned in docs here learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/…. The issue OP had was probably related to the async void signature (which I inadvertently fixed).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.