Zerbu
Zerbu

Reputation: 585

MVVM: What is the purpose of a separate ViewModel?

If the code-behind for the View is meant to consist of nothing but the constructor with the InitializeComponent() call, why not just use DataContext="{Binding RelativeSource={RelativeSource Self}}" and use the view itself as a view model?

I get that this technically violates the Single Responsibility Principle, but since the XAML and code-behind are defined independently from each other, it doesn't cause the usual mess. Having separate view models for everything causes more mess to the file structure.

Upvotes: 2

Views: 914

Answers (1)

ad1Dima
ad1Dima

Reputation: 3195

ViewModel describes view state. For testing and reusing purposes it must be UI independent. Benefits:

  1. You can cover ViewModel by unit tests and you haven't to refer UI classes in test
  2. You can reuse your ViewModel on other UI targets: console app, WinForms App, UWP app, Xamarin iOS/Android App, no display IoT project. You'll need to write only view for new target platform.
  3. Sometimes even in WPF and MVVM you have to write some code behind for View-only purpose because it may be much more simpler, readable and reliable then create some new entity for that. And you'll get mess if you have also ViewModel in code behind.

Upvotes: 5

Related Questions