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

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

10-13 17:11