MVVM中的命令 [英] Commands in MVVM

查看:196
本文介绍了MVVM中的命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过教程,人们在他们的代码中创建CanExecute等方法。我假设他们正在这样做,以帮助读者了解它是如何工作的。当我查找命令和ICommand它需要我到MSDN上的ICommand类,用于Windows应用商店应用程序。是否有WPF的Command类?

I've been seeing tutorials where people are creating the methods like CanExecute in their code. I'm assuming they are doing this to help the reader understand how it all works. When I look up Command and ICommand it takes me to the ICommand class on MSDN that is used for Windows Store apps. Is there not a Command class for WPF?

推荐答案

ICommand 在WPF中是 RoutedCommand (及其兄弟 RoutedUICommand )。 RoutedCommand 的工作方式如下:

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


RoutedCommand 上的code>和方法不包含
命令的应用程序逻辑如同典型的
ICommand 的情况,而是这些方法引发遍历
元素树的事件,寻找具有 CommandBinding 。附加到 CommandBinding 的事件
处理程序包含命令逻辑。

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.

这样做的问题是,这些事件处理程序必须连接到视图的代码隐藏,这正是你不想在MVVM中做的。

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.

教程你在代码中看到 CanExecute 方法(我们真正的意思是代码 code> ICommand 实现)使用自定义命令实现,例如 DelegateCommand RelayCommand 被设计为将它们的 CanExecute / 逻辑转发到即时提供的功能;

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.

这些实现通常由MVVM框架提供(对于这两个示例,框架分别是Prism和MVVM Light) ,但他们真的很简单(都是开源,抓取代码并读取它),没有什么阻止你复制/粘贴代码,如果你不想要整个框架。

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.

你可以总结上面的内容是在WPF中内置了一个命令类,但是在MVVM的上下文中并不真正有用。

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".

这篇关于MVVM中的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆