-1

I have a button like this:

<Button x:Name="buttonGetData" Width="70" Content="GetData" Command="{Binding SaveCommand}"  />

I want when The Save Command executed until it's not completed the user cant click on my button or if clicked on my button my command not execute! my solution for this problem is

 bool execute;
private void MyCommandExecute(CommandParam parm)
{
  if(execute)return;
  execute=true;
  ///Some actions
  execute=false;

}

Is there a better solution for this problem?

M.Azad
  • 3,673
  • 8
  • 47
  • 77

1 Answers1

1

The ICommand interface also defines a CanExecute method. It's possible for you to make that command return false when the execution starts, and set it back to true when it's done. This also gives you the benefit of having the button disabled during the command's execution.

I don't work with RelayCommand, so I'm not sure if it has an equivalent to DelegateCommand's RaiseCanExecuteChanged method, but using DelegateCommand (which essentially does the same thing as RelayCommand), you could do something like this (note that this implementation isn't thread safe):

SaveCommand = new DelegateCommand<CommandParam>(MyCommandExecute, MyCommandCanExecute);

private bool  canExecute;
private bool MyCommandCanExecute()
{
    return canExecute;
}

private void MyCommandExecute(CommandParam parm)
{
    // Change the "can execute" status and inform the UI.
    canExecute = false;
    SaveCommand.RaiseCanExecuteChanged();

    DoStuff();

    // Change the "can execute" status and inform the UI.
    canExecute = true;
    SaveCommand.RaiseCanExecuteChanged();
}
M.Azad
  • 3,673
  • 8
  • 47
  • 77
Adi Lester
  • 24,731
  • 12
  • 95
  • 110