user2525395
user2525395

Reputation: 111

WPF: How to organize viewmodels in MVVM?

I'm building a large scale WPF application and I want to know if this is the correct way to organize my program using the MVVM pattern.

The program holds a database of information on the general population of people in their respective regions in a Tree. This tree and/or list of people will be shared across all viewmodels to display demographics into vairous charts. These various charts are displayed to the View in different tabs.

Currently, I have a static tree to contain the information of people and each xaml page will correspond to a tab in the main window. Each tab is bound to its own viewmodel, but that viewmodel inherits the mainviewmodel so that information in the mainviewmodel can be shared across all viewmodels.

Ex:

MainViewModel.cs - (Contains the tree, list<people>, and other variables)
Tab1ViewModel.cs - (Inherits MainViewModel)
Tab2ViewModel.cs - (Inherits MainViewModel and maybe Tab1ViewModel)
Tab3...etc

MainWindow.xaml - Datacontext = MainViewModel
Tab1View.xaml - Datacontext = Tab1ViewModel
Tab2View.xaml - Datacontext = Tab2ViewModel
Tab3...etc

Is this the proper way of setting up the MVVM pattern? I don't know a better or simpler way of sharing the static data across different views.

Upvotes: 1

Views: 907

Answers (2)

sondergard
sondergard

Reputation: 3234

Inheriting from a class will not result in sharing the variables. Whenever an instance of Tab1ViewModel, a new instance of all the variables in MainViewModel would also be created, and so the data is not shared to Tab2ViewModel (which in turn has its own copy).

Also, I prefer a one to one between a view and a viewmodel - meaning that a Tab1ViewModel should not be concerned with MainViewModel logic. To share common behavior (property changed event, basic validations etc) between view models, you could make an abstract ViewModelBase. Furthermore view models should generally not "know" about each other. Instead information should flow between them through centralized messages.

The problem about how to share the data is not really related to MVVM. The simplest approach is to load the data centrally, and pass it in the constructor of each view model, but a more elegant solution would be to use Dependency Injection. It takes some time to learn, but I would highly recommend it.

Upvotes: 2

Clyde
Clyde

Reputation: 8145

The only thing that really jumps out at me is that your tabs are inheriting from the MainViewModel -- that really doesn't make a lot of sense, since that makes them a separate copy.

It sounds like the Tab view models should contain a reference to your (singleton, or similar) main view model, or maybe just an interface that exposes the needed fields like SelectedPerson or something like that

Upvotes: 1

Related Questions