Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding WPF - store Data in Model or ViewModel

Tags:

c#

mvvm

wpf

I am unsure where to store Data in a WPF Application. There are two principles that might collide. Could somebody please clear this up?

Principle 1: Data should be stored in the Model.
It follows, that for example an ObservableCollection<string> Articles should be stored in the Model. A Property in the ViewModel could make it available to the View.

Principle 2: States relying on the View should be stored in the ViewModel.
That means that the string _SelectedArticle variable with corresponding Property string SelectedArticle should be stored in the ViewModel.

So far, I've put only Methods or values that don't affect the View into the Model, because I (maybe too) strongly followed principle 2. But I'm not sure if this is the right approach.

Should I really keep some Data in the Model and some in the ViewModel or is there a place to store all the data?

like image 501
Breeze Avatar asked Dec 05 '25 11:12

Breeze


1 Answers

The simple answer would be: data should be stored where it belongs.

  • The Model should contain only data itself - it may contain data that you got from external services, user input, data access layer and other.
  • ViewModels should wrap parts of the data, which will be presented to the user, into proper wrappres to provide users with the ability to view and change data - public properties, ObservableCollections, etc. If there are many visual representations of the same data in your app, then you must build appropriate ViewModel for each representation (View).
  • View consumes ViewModel, but additionally can have (and store) some validation (not verification) logic and associated parameters in it.

In your case the Model should have List<string> Articles. ViewModel will consume this list and build ObservableCollection<string> Articles in the constructor. And SelectedArticle should be stored in ViewModel too, if its value used only for navigating within View and will never be used in Model or saved to DB somewhere in Data Access Layer.

like image 197
Mikhail Tumashenko Avatar answered Dec 07 '25 00:12

Mikhail Tumashenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!