Search code examples
c#wpfmvvmwpf-controlskey-bindings

How to prevent multiple consecutive 'Enter' key press on a button


I have a button, When I press 'Enter' Key through Keyboard, the button command executes. When I consecutively press the 'Enter' key, the command also executes multiple times which I don't want.

I want to restrict the behaviour to single execution of command even during multiple 'Enter' key press. Can somebody help ?

View.xaml

<Button x:Name="btnSearch" IsDefault="True"  Content="Search"  Command="{Binding SearchButtonCommand}">
      <Button.InputBindings>
          <KeyBinding Command="{Binding Path=SearchButtonCommand}" Key="Return" />
      </Button.InputBindings>
</Button>

ViewModel.cs

public ICommand SearchButtonCommand
{
 get { return new DelegateCommand(SearchButtonExecutionLogic); }
}

Solution

  • The easiest way to reach your goal is to introduce and check some flag isSearchRunning in your command implementation in ViewModel:

    private bool isSearchRunning = false;
    private void SearchButtonCommandImpl()
    {
        if (isSearchRunning)
        {
            return;
        }
        try
        {
            isSearchRunning = true;
            //Do stuff
        }
        finally
        {
            isSearchRunning = false;
        }
    }