Commands in MVVM

落爺英雄遲暮 提交于 2019-12-05 11:40:33

The built-in implementation of ICommand in WPF is RoutedCommand (and its sibling RoutedUICommand). RoutedCommand works like this:

The Execute and CanExecute methods on a RoutedCommand do not contain the application logic for the command as is the case with a typical ICommand, but rather, these methods raise events that traverse the element tree looking for an object with a CommandBinding. The event handlers attached to the CommandBinding contain the command logic.

The problem with this is that these event handlers must be attached to the code-behind for your view, which is exactly what you do not want to do in MVVM.

Tutorials where you see CanExecute methods in code (and by that we really mean code outside the ICommand implementation) are using custom command implementations such as DelegateCommand and RelayCommand which are designed to "forward" their CanExecute/Execute logic to functions provided on the fly; typically, those are methods on the viewmodel that exposes the command.

These implementations are usually provided by MVVM frameworks (for these two examples the frameworks are Prism and MVVM Light respectively), but they are really simple (both are open source, grab the code and read it) and there's nothing stopping you from copy/pasting the code if you don't want the whole of the framework.

You could summarize the above as "there is built-in a command class in WPF, but it's not really useful in the context of MVVM".

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!