Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does calling View Model methods in Code Behind events break the MVVM?

Tags:

c#

mvvm

wpf

I wonder if that would break the MVVM pattern and, if so, why and why is it so bad?

WPF:

<Button Click="Button_Click" />

Code Behind:

private void Button_Click(object sender, RoutedEventArgs e)
{
    ViewModel.CallMethod();
}

View Model:

public void CallMethod()
{
    // Some code
}

IMHO, it keeps the code behind quite simple, the view model is still agnostic about the view and code behind and a change to the view doesn't affect the business logic.

It seems to me more simple and clear than Commands or CallMethodAction.

I don't want the kind of answer "it is not how it should be done". I need a proper and logical reason of why doing so could lead to maintenance or comprehension problems.

like image 450
Sébastien Avatar asked Oct 20 '16 17:10

Sébastien


People also ask

How the model changes could be notified to ViewModel in MVVM?

If you want your Models to alert the ViewModels of changes, they should implement INotifyPropertyChanged, and the ViewModels should subscribe to receive PropertyChange notifications. But typically this is only needed if more than one object will be making changes to the Model's data, which is not usually the case.

Should the ViewModel have a reference to the view?

Caution: A ViewModel must never reference a view, Lifecycle , or any class that may hold a reference to the activity context.

Is MVVM event driven?

Invested by Microsoft architects Ted Peters and Ken Cooper, MVVM typically simplifies user interfaces' event-driven architecture.


1 Answers

Nope, this is perfectly fine.

It's the View's job to handle user input and interact with the ViewModel. A button click event-handler, which calls a method of the ViewModel in response, falls quite cleanly into this role.

What you have posted is clean, readable, efficient, maintainable, and fully in the spirit of the MVVM design pattern.

Now, in a more general sense, what you really want to ask is: "why choose ICommands, vs Event Handlers for MVVM?" Well, you certainly wouldn't be | the | first.

like image 153
BTownTKD Avatar answered Oct 13 '22 08:10

BTownTKD