Why use commands in MVVM

耗尽温柔 提交于 2019-12-31 03:55:26

问题


I'm actually learning MVVM pattern.

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.


回答1:


Why use commands?

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".

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.

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.

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.

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




回答2:


Another benefit from using ICommand is its bool CanExecute() method. You can monitor and control the state and define conditions when your ICommand can and will be invoked. Plus, for example, Button with bound ICommand disables itself automatically, if CanExecute() returns false (do not forget to call CanExecuteChanged() method of ICommand every time the propert(y/ies), which affect(s) CanExecute(), change(s) its/their value). By the way, the semantic of usage of this pattern is described in other answers.



来源:https://stackoverflow.com/questions/30343129/why-use-commands-in-mvvm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!