MVVM, Should I use ICommand on all controls?

4

The use of commands through the ICommand interface is part of the MVVM. The question is, should I use commands on all controls? Even those who are not connected with the business rule? For example, a HambugerButton whose sole purpose is to expand or collapse HambugerMenu . Should I apply Command to it too?

    
asked by anonymous 31.12.2016 / 21:06

1 answer

2

Yes, my opinion is that you should use Commands in all situations, because it maintains the consistency of the MVVM pattern and does not cause confusion, because mixing code-behind with MVVM will cause a to tinker with your code because the features will be mixed in different parts of the code.

For example, look at how a MVVM ployment gets clean and straightforward:

Using the example of opening a control with a button.

// XAML - HamburgerMenu
<controls:HamburgerMenu IsOpen={binding MenuIsOpen} />

The Boolean property IsOpen of HambugerMenu has been bound to a Boolean property of my view-model called MenuIsOpen .

// View-Model
public bool MenuIsOpen { get; private set; } // Implementar INotifyPropertyChanged

You have the button that expands (opens) HamburgerMenu .

 // XAML - Button
 <controls:Button Command={binding OpenMenu} />

The button command was connected to ICommand of my view-model named OpenMenu .

// View-Model
public ICommand OpenMenu = new RelayCommand(OpenMenuCommand);

private void OpenMenuCommand()
{
   MenuIsOpen = !MenuIsOpen; // Alterna entre aberto e fechado.
}

Ready, this way you switch between open and closed your HamburgerMenu, no events, no code-behind, no surprise code.

In the example above, any method within your view-model can control the opening and closing of your hamburgerMenu through the MenuIsOpen property, which is very good for code reuse because if there is any routine in which you you need to control the opening of the control, it is already available to you, which would not be possible with code-behind (not in a clean way), so you continue in the MVVM pattern, have a clean code, your view contains only bindings , the view-model does not even know about the controls.

    
04.10.2017 / 16:19