本文介绍了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?

推荐答案

如您所见,RoutedCommandICommand接口的一个实现,主要区别在于它的功能类似于RoutedEvent:

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 的事件处理程序包含命令逻辑.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-15 02:21