ICommand与RoutedCommand [英] ICommand vs RoutedCommand

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

问题描述

让我们将按钮Command属性绑定到自定义命令.

Let's have a button Command property bound to a custom command.

何时应实现ICommand以及何时从RoutedCommand派生?我看到 RoutedCommand实现了ICommand .

When should I implement ICommand and when derive from RoutedCommand? I see that RoutedCommand implements ICommand.

在哪种情况下我需要实现ICommand? MVVM模型呢?哪个更适合此目的?

In which case could I need to implement an ICommand? What about MVVM model? Which one suits better for this purpose?

推荐答案

您已经注意到

As you have noticed the RoutedCommand class is an implementation of the ICommand interface, its main distinction if that its function is similar to that of a RoutedEvent:

RoutedCommand上的Execute和CanExecute方法不像典型的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.

Execute方法引发PreviewExecuted和Executed事件. CanExecute方法引发PreviewCanExecute和CanExecute事件.

The Execute method raises the PreviewExecuted and Executed events. The CanExecute method raises the PreviewCanExecute and CanExecute events.

如果您不希望RoutedCommand的行为,您将查看自己的ICommand实现.至于MVVM模式,我不能说一个解决方案,似乎每个人都有自己的方法.但是,以下是我遇到的一些解决此问题的方法:

In a case when you don't want the behavior of the RoutedCommand you'll be looking at your own implementation of ICommand. As for the MVVM pattern I can't say that one solution, it seems that everyone has their own methodology. However, here are a few approaches to this problem that I've come across:

  • Using RoutedCommands with a ViewModel in WPF
  • Relaying Command Logic
  • Simple Command (almost identical to Relay Command but worth reading)

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

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