WPF:MVVM:命令与CallMethodAction? [英] WPF: MVVM: Command vs CallMethodAction?

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

问题描述

我正在通过一个新的(小型)项目学习MVVM模式,我对在控制器上调用动作的方式有一个疑问:

I'm learning the MVVM pattern with a new(small) project, and I've one question about the way to invoke actions on our controller:

我看到了很多教程,他们在其中告诉我们使用Command,这意味着声明一个RelayCommand,对其进行初始化并创建RelayCommand调用的动作.

I saw many tutorial where they were telling us to use Command, implying to declare a RelayCommand, initialize it and create the action called by the RelayCommand.

另一方面,我有一位同事说我可以将CallMethodAction与触发器一起使用:

In the other side, I've a colleague which said me that I can use the CallMethodAction with a trigger:

<i:Interaction.Triggers> 
  <i:EventTrigger> 
    <ei:CallMethodAction MethodName="Init" TargetObject="{Binding}" /> 
  </i:EventTrigger> 
</i:Interaction.Triggers> 

对我来说,他的方法具有以下优点:我不必为命令创建某些init方法(可能永远不会使用).

For me, his approach has the advantage that I don't have to make some inits methods for commands(which may be never used).

那我想念什么?为什么每个人都使用命令?

So what am I missing? Why everybody use commands?

推荐答案

命令提供了用于禁用ViewModel代码的功能.这可以用来自动禁用例如绑定到命令的按钮.这就是使Commands更好的原因.此外,根据您的逻辑,您可以动态地在同一插槽中拔出另一个Command,它将从View重新路由流量,而在CallMethodAction中,您将不得不在被调用的方法中编写重新路由逻辑,这很丑陋.

Commands provide functionality for disabling in ViewModel code. That can be used to automatically disable e.g buttons bound to command. That's what makes Commands better. Besides, based on your logic you could just dynamically pluck another Command in the same slot and it will reroute the traffic from View, whereas in CallMethodAction you would have to write the rerouting logic in the called method, which would be ugly.

如您所见,这取决于您要完成的工作以及您的逻辑有多复杂:)

As you can see, it depends on what you try to accomplish and how complicated is your logic :)

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

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