![](/img/trans.png)
[英]What is the difference between ActionCommand and DelegateCommand
[英]Difference between Delegatecommand, relaycommand and routedcommand
我對命令模式感到困惑。 關於命令有很多不同的解釋。 我以為下面的代碼是delegatecommand,但是在閱讀relaycommand 之后,我有疑問。
中繼命令、委托命令和路由命令之間有什么區別。 是否可以在與我發布的代碼相關的示例中顯示?
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; }
}
}
您的FindProductCommand
類實現了ICommand
接口,這意味着它可以用作WPF command 。 它既不是DelegateCommand
也不是RelayCommand
,也不是RoutedCommand
,它們是ICommand
接口的其他實現。
FindProductCommand
VS DelegateCommand
/ RelayCommand
通常,當ICommand
的實現命名為DelegateCommand
或RelayCommand
,目的是您不必編寫實現ICommand
接口的類; 相反,您將必要的方法作為參數傳遞給DelegateCommand
/ RelayCommand
構造函數。
例如,你可以這樣寫,而不是整個班級:
ProductViewModel _avm;
var FindPoductCommand = new DelegateCommand<object>(
parameter => _avm.FindProduct(),
parameter => _avm.CanFindProduct()
);
(另一個可能比節省樣板代碼更大的好處——如果您在視圖模型中實例化DelegateCommand
/ RelayCommand
,您的命令可以訪問該視圖模型的內部狀態。)
DelegateCommand
/ RelayCommand
一些實現:
DelegateCommand
的ICommand
WPF 教程實現DelegateCommand
RelayCommand
的原始實現有關的:
FindProductCommand
VS RoutedCommand
您的FindProductCommand
將在觸發時執行FindProduct
。
WPF 的內置RoutedCommand
執行其他操作:它引發路由事件,該事件可由可視化樹中的其他對象處理。 這意味着可以附加一個命令結合那些其他對象來執行FindProduct
,而附接RoutedCommand
本身具體地,涉及觸發命令,例如一個按鈕,菜單項,或上下文菜單項的一個或多個對象。
一些相關的SO答案:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.