我一直在看到人们在他们的代码中创建像 CanExecute 这样的方法的教程。我假设他们这样做是为了帮助读者理解这一切是如何运作的。当我查找 Command 和 ICommand 时,它会将我带到 MSDN 上用于 Windows 应用商店应用程序的 ICommand 类。 WPF 没有 Command 类吗?
最佳答案
ICommand
的内置实现在 WPF 中是 RoutedCommand
(及其兄弟 RoutedUICommand
)。 RoutedCommand
像这样工作:
The
Execute
andCanExecute
methods on aRoutedCommand
do not contain the application logic for the command as is the case with a typicalICommand
, but rather, these methods raise events that traverse the element tree looking for an object with aCommandBinding
. The event handlers attached to theCommandBinding
contain the command logic.
这样做的问题是这些事件处理程序必须附加到您的 View 的代码隐藏中,而这正是您不想在 MVVM 中执行的操作。
您看到的教程
CanExecute
代码中的方法(我们实际上指的是 ICommand
实现之外的代码)正在使用自定义命令实现,例如 DelegateCommand
和 RelayCommand
旨在“转发”他们的 CanExecute
/Execute
动态提供的功能的逻辑;通常,这些是 View 模型上公开命令的方法。这些实现通常由 MVVM 框架提供(对于这两个示例,框架分别是 Prism 和 MVVM Light),但它们非常简单(两者都是开源的,获取代码并阅读它)并且没有什么可以阻止您复制/粘贴如果您不想要整个框架,请查看代码。
您可以将上述内容总结为“WPF 中内置了一个命令类,但它在 MVVM 的上下文中并没有真正有用”。
关于wpf - MVVM 中的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15248842/