2013-01-06 50 views
39

我對命令模式感到困惑。關於命令有很多不同的解釋。我認爲下面的代碼是delegatecommand,但是在閱讀了關於relaycommand之後,我對此有所懷疑。Delegatecommand,relaycommand和routedcommand之間的區別

relaycommand,delegatecommand和routedcommand有什麼區別。是否可以在與我的發佈代碼相關的示例中顯示?

class FindProductCommand : ICommand 
{ 
    ProductViewModel _avm; 

    public FindProductCommand(ProductViewModel avm) 
    { 
     _avm = avm; 
    } 

    public bool CanExecute(object parameter) 
    { 
     return _avm.CanFindProduct(); 
    } 

    public void Execute(object parameter) 
    { 
     _avm.FindProduct(); 
    } 

    public event EventHandler CanExecuteChanged 
    { 
     add { CommandManager.RequerySuggested += value; } 
     remove { CommandManager.RequerySuggested -= value; } 
    } 

} 
+0

你做了谷歌搜索..看看這裏的例子嘗試的代碼,並將其應用到你有什麼.. http://msdn.microsoft.com/en-us/library/ff654132.aspx http://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.mvvm.relaycommand.aspx http:///msdn.microsoft.com/en-us/library/ system.windows.input.routedcommand.aspx – MethodMan

+1

是的,它沒有太大的幫助 – Zaz

+0

我會建議在谷歌搜索命令模式的谷歌搜索然後 – MethodMan

回答

43

FindProductCommand類實現ICommand接口,這意味着它可以被用作WPF command。它既不是DelegateCommand也不是RelayCommand,也不是RoutedCommand,它們是ICommand接口的其他實現。


FindProductCommand VS DelegateCommand/RelayCommand

一般來說,當ICommand實現被命名爲DelegateCommandRelayCommand,其用意是,你不必編寫一個實現ICommand接口的類;相反,您將必要的方法作爲參數傳遞給構造函數DelegateCommand/RelayCommand

例如,而不是你的整個類的,你可以寫:

ProductViewModel _avm; 
var FindPoductCommand = new DelegateCommand<object>(
    (parameter) => _avm.FindProduct(), 
    (parameter) => _avm.CanFindProduct() 
); 

DelegateCommand/RelayCommand一些實現:

相關:


FindProductCommand VS RoutedCommand

您的FindProductCommand觸發時將執行FindProduct

WPF的內置RoutedCommand做了其他事情:它引發了一個routed event,它可以由視覺樹中的其他對象處理。這意味着您可以附加綁定到這些其他對象的命令來執行FindProduct,同時將RoutedCommand本身專門附加到一個或多個觸發命令的對象,例如,按鈕,菜單項或上下文菜單項。

一些SO相關答案: