如何防止连续按下多个“ Enter”键

时间:2018-10-05 06:25:48

标签: c# wpf mvvm wpf-controls key-bindings

我有一个按钮,当我通过键盘按下“ Enter”键时,将执行按钮命令。当我连续按Enter键时,该命令还会执行多次,这是我不希望的。

我想将行为限制为即使在多次“ Enter”键按下时也只能执行一次命令。有人可以帮忙吗?

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

1 个答案:

答案 0 :(得分:2)

最简单的方法是在ViewModel的命令实现中引入并检查一些标志isSearchRunning

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