2012-06-16 39 views
-1

我有這樣一個按鈕:如何控制中繼命令的執行?

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

我想,當save命令或執行,直到它沒有完成用戶斜面點擊我的按鈕,如果在我的按鈕點擊我的命令不執行! 我對這個問題的解決方案是

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

} 

是有這個問題更好的解決辦法?

+0

而且這個工作適合你嗎?除非「一些行動」涉及線程,否則不需要做任何事情。 –

+0

@HenkHolterman是它爲我工作。 –

回答

1

ICommand接口還定義了一個CanExecute方法。執行開始時,您可以使該命令返回false,並在完成後將其設回true。這也爲您提供了在命令執行過程中禁用按鈕的好處。

我不RelayCommand工作,所以我不知道它是否有一個相當於DelegateCommandRaiseCanExecuteChanged方法,但使用DelegateCommand(基本上做同樣的事情RelayCommand),你可以做這樣的事情(注意這個實現不是線程安全的):

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