0

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); }
}
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
DotNetSpartan
  • 931
  • 4
  • 20
  • 41
  • For this Problem I added a timer, and when enter is send I block sending enter again for, let's say, 2 seconds – Shmosi Oct 05 '18 at 06:28
  • 1
    many ways you can do that. may be a timer , or removing the click event from the button after first click , or making the button as non clickable after first click, or you can you Jquery .one(), or just have a global flag and make it's value false after first click and you can write a condition check after click etc.. – Arunprasanth K V Oct 05 '18 at 06:33
  • [Related?](https://stackoverflow.com/questions/8001450/c-sharp-wait-for-user-to-finish-typing-in-a-text-box) – ProgrammingLlama Oct 05 '18 at 06:34
  • how about change focus after key entered? – Arphile Oct 05 '18 at 06:35

1 Answers1

2

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;
    }
}
Rekshino
  • 6,954
  • 2
  • 19
  • 44
  • If you do this, it's a good idea to provide the user with some feedback when the flag is set. You could disable the button, or change it's caption to 'running', or display a messagebox when the button is clicked a second time. – Robin Bennett Oct 05 '18 at 08:12
  • @RobinBennett Yes, there are many possibilities how a state of ViewModel (namely `IsSearchRunning`) can be represented in the View. – Rekshino Oct 05 '18 at 08:28