Sébastien Sébastien - 1 year ago 80
C# Question

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

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


<Button Click="Button_Click" />

Code Behind:

private void Button_Click(object sender, RoutedEventArgs e)

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

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download