Is the common implementation of RelayCommand violating the MVVM pattern? Is the common implementation of RelayCommand violating the MVVM pattern? wpf wpf

Is the common implementation of RelayCommand violating the MVVM pattern?


This is an easy and quick & dirty implementation mostly only used for tutorial cases that do not tie the tutorial to a specific MVVM framework, but act as a generic do-it-yourself MVVM tutorial.

This approach - other than tight coupling - has several other disadvantages.

When the CommandManager.InvalidateRequerySuggested() method is called, the CanExecute method of every command will be called. If you have 100s of commands in your Application, this can have severe impact on performance of your WPF Application.

I personally always suggest using a matured MVVM Framework (Prism being my favorite for LoB applications). There the commands usually don't implement it this way but you call MyCommand.OnCanExecuteChanged() (in case of Prism) to trigger CanExecute validation for one single command.

If you have compound or multiple commands that depend on each other, you tie it yourself in code, i.e. by storing a list of related commands inside the view they are used and loop through it or registering their OnCanExecuteChanged() methods to a multicast delegate and calling that instead.

Is this implementation violating the MVVM pattern?

Technically yes.

Or do you maybe place the RelayCommand in your view somehow?

Not really, though you may be able to abstract it with an external factory, it do not seems to make sense (see the issue above)

If this is indeed flawed, is there a best practice implementation that solves this issue?

Don't have a global invalidation of commands state anyway. Tie the commands yourself that need their execution state tied together.