简体   繁体   中英

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); }
}

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM