c# – The general scheme of event handling in the MVVM pattern

Question:

I want to find out the event handling scheme when using the MVVM pattern.

  1. As I understand it, there should not be a single event handler in the code, since they are possible only in the code behind, and it's bad to use it, right?
  2. All event handling happens through commands. To do this, you need to write a simple class like this, in which to insert your delegates, create command properties and bind them to elements?

     class RelayCommand : ICommand { private Action<object> _executeDelegate; public RelayCommand(Action<object> executeDelegate) { _executeDelegate = executeDelegate; } public bool CanExecute(object parameter) { return true; } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { _executeDelegate(parameter); } }
  3. And how to handle different events from the same element? As I understand it, the command is executed for some one "main" event?

  4. Is it possible to get the event arguments (the same arguments as a normal handler)?
  5. Are there any prettier methods? For example, through command binding? But how can these bindings be added to the window if the ViewModel does not have a link to it?

Answer:

1, 2. For my taste, not really.

The right place for event handlers is UI-specific jobs. For example, you want to measure some control, and if its width is less than 10% of the container, then hide it completely. To do this, you subscribe to the resize event. This is a specific task of the presentation layer, which has nothing to do with the VM. Using a command for it is wrong, you don't need weak coupling here.

3. Normally, an element should not have two commands in its interface. For example, for a button, the only event that the VM layer might be interested in is pressing the button itself. Changing the size of the button for the VM is of no interest. Accordingly, the button ( Button ) has only one command.

If you are writing a custom control that can actually produce several different interesting events for the VM level, define several commands in it.

4. Can't add anything to @ixSci's point of view: there's a CommandParameter for that.

5. It is possible to further reduce connectivity by using predefined commands. Example: a menu item can declare as its command the predefined command ApplicationCommands.Save ( <MenuItem Header="Сохранить" Command="Save" ... /> ), and bind the implementation of the Save command somewhere else in the code (see CommandBinding ) .

Scroll to Top