WPF的ICommand VS的RoutedCommand(WPF ICommand vs Rout

2019-06-26 02:23发布

让我们有一个按钮Command绑定到自定义命令属性。

当我应该实现ICommand并从获得时RoutedCommand ? 我看到的RoutedCommand实现ICommand的

在这种情况下,我可能需要iplement一个ICommand ? 什么MVVM模型? 哪一个适合用于此目的的更好吗?

Answer 1:

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:

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.

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

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)


Answer 2:

我想补充到丰富的麦圭尔的回答的唯一的事情就是RoutedCommands(和他们的更普遍的后裔RoutedUICommand必须连线了事件处理程序才能正常工作。

大多数MVVM实现我所遇到试图利用对视图模型绑定,因此视图模型(而不是视图)拥有CanExecute /执行逻辑。

相比之下,事件处理程序动议负担的视角。 然后处理可以传播到视图模型,但这意味着一个稍高程度视图模型和视图(铸造+方法调用等)之间的耦合。



文章来源: WPF ICommand vs RoutedCommand