What's the point of having models in WPF?
c#, mvvm, wpf
Solution
If you think of it as an abstraction, let's say you need to build a screen to display a list of Employees and make a Selection, Search or Filter. Then we break it up in components. You will require:
- An `Employee` class (Model)
- An `EmployeeManagementViewModel` to prepare and present your list of Employees and manage state changes for your View (e.g. can contain a `SelectedEmployee`, Filter Search text, etc) to be used by your `EmployeeManagementView`
- A list of Employees (Which will live in your `EmployeeManagementViewModel`)
Most likely you will already have an `Employee` class. If that's the case then you just need to expose that model in your `EmployeeManagementViewModel` as an `ObservableCollection` of Employees.
In case you don't already have an Employee class you may decide to create an `EmployeeViewModel` and add your `Employee` properties there like `FirstName`, `LastName`, etc.
Technically this will work but conceptually it bothers me because an `EmployeeViewModel` is not an Employee (it contains an employee). If you're abstracting reality then, the blueprint of an Employee should not include properties or methods to be used by a View. To me Employee should be a POCO which could implement `INotifyPropertyChanged` and nothing more than that. You're separating View state from the Model itself. Having an Employee POCO makes it easier to UnitTest, create mock employees, map it to a database table through an ORM, etc.
As the name implies the ViewModel is the model for your View and the Model is the model for your business domain
Anyway that's how I see it. When I started doing MVVM work I had that same question but over the years seems like it makes sense.
Problem
So far I have yet to see the value of having models in WPF. All my ViewModels, by convention, have an associated Model. Each of these Models is a virtual clone of the their respective ViewModel. Both the ViewModel and Model classes implement `INotifyPropertyChanged` and the ViewModel just delegates everything to the Model anyway. Why bother having Models then? Why can't I just move my Model logic up into the ViewModel and call it a day? It seems rather redundant (that is, not DRY) to have MVVM, and just use VVM by default unless some special edge case demands a Model. If using explicit model classes better supports unit testing, for example, or some other best practice, I can see the value.