问题描述
让我们将按钮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?
推荐答案
您已经注意到 RoutedCommand
类是ICommand
接口的实现,如果其功能类似于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:
- 在WPF中将RoutedCommands与ViewModel一起使用
- 中继命令逻辑
- 简单命令(与中继命令几乎相同,但值得一读)
- Using RoutedCommands with a ViewModel in WPF
- Relaying Command Logic
- Simple Command (almost identical to Relay Command but worth reading)
这篇关于ICommand与RoutedCommand的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!