I understand that in MVVM:
So how does the ViewModel respond to actions that the user does on the View, e.g. type something into a TextBox or move a slider, etc.
I understand that this is done with RoutedEvents but almost all RoutedEvent examples I find use CodeBehind in the View, which is exactly what you don't have anymore in MVVM.
So that leaves RoutedCommands which I find more examples of in MVVM but e.g. moving a slider really isn't a command in that sense, it is an event, so I am wondering if this is really what should be used.
Then I read advice such as "In MVVM use RoutedEvents as little as possible, and no RoutedCommands at all." OK.
So that leaves, e.g. in the WPF Model-View-ViewModel Toolkit 0.1 project form the WPF team themselves you have a "DelegateCommand" which also looks like an interesting way.
Then some people are also using "RelayCommand".
This is a lot of choices and confusion for doing something so core to developing applications.
What is the best way to simply do in MVVM what we were doing for the last 10 years with Code Behind:
The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.
The purpose of the ViewModel is to acquire and keep the information that is necessary for an Activity or a Fragment. The Activity or the Fragment should be able to observe changes in the ViewModel. ViewModels usually expose this information via LiveData or Android Data Binding.
In fact - the ViewModel shouldn't care about the View at all. It should simply make data available through properties, and it's up to the View to decide what it will dynamically bind to in the ViewModels. If the ViewModel wants to tell the View something this should occur implicit through Bindings.
Just to be clear, when people mention DelegateCommand and RelayCommand, they are really talking about the same thing: an implementation of ICommand that allows you to pass in a delegate. You can use them interchangeably.
As far as I am concerned, having your view (XAML) bind to DelegateCommands in the ViewModel is the best way to implement MVVM.
I stay away from RoutedEvents AND code-behind whenever possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With