为什么在MVVM中使用命令 [英] Why use commands in MVVM

查看:84
本文介绍了为什么在MVVM中使用命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上正在学习MVVM模式.

I'm actually learning MVVM pattern.

我对命令一无所知.为什么要使用它们?为什么不只使用调用ViewModel函数的函数(在View中)?哪些命令为我们提供了?显然,它们被广泛使用,但是我找不到原因.

I can't understand one thing about commands. Why use them? Why don't just use a function (in the View) which call a ViewModel's function? What commands provide us? Apparently they are widely used, but i can't find why.

推荐答案

为什么使用命令?

Why use commands?

因为命令提供了封装.您可以在ICommand中隐藏任何复杂的逻辑,并且可以在需要时交换实现.这样您的View不需要了解有关ViewModel等方法的任何信息.它只需要知道ViewModel提供了执行"x"操作的命令即可.

Because commands provide encapsulation. You can hide any kind of complex logic inside a ICommand and you can swap the implementation whenever you need. So that your View doesn't need to know anything about your methods of ViewModel etc. It just needs to know ViewModel provides a command to do operation "x".

ICommand接口还受许多框架元素(如ButtonMenuItem等)支持.当您拥有ICommand时,可以将其绑定到View -它将负责执行命令

More than that ICommand interface is supported by many framework elements like Button, MenuItem etc. When you have a ICommand you can bind it to the View --it will take care of executing the command.

为什么不仅仅使用一个函数(在View中)来调用ViewModel的 功能?

Why don't just use a function (in the View) which call a ViewModel's function?

因为我们不想混淆职责.视图不应该有任何逻辑,这只是愚蠢的事情,它只是向用户显示数据.没有了.

Because we don't want to mix up the responsibilities. View shouldn't have any logic, it is just a dumb thing which just displays the data to the user. No more.

假设您认为自己的逻辑.有一天,您的经理可以站出来说我们不再需要这个用户界面了(看起来不太好).使它具有吸引力.不仅必须重新设计View,而且还需要在其中重复View中的逻辑.这是重复的工作(违反DRY原理),因为您的用户界面已更改等原因,可能会引入新的错误.

Assume if you have logic in your view. One day your manager can come up and say we don't need this UI anymore(it doesn't looks good). Make it something attractive. Not only the View have to be redesigned, but you need to repeat the logic in View there. This is repeated work(against DRY principle), can introduce new bugs because your UI has changed etc.

将视图和逻辑分开的另一个主要优点是,您可以轻松地对逻辑进行单元测试(在ViewModel和Model中).

Another main advantage of separating the View and Logic is that you can easily unittest the Logic (in ViewModel and Model).

这篇关于为什么在MVVM中使用命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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